哪里应该在Redux中进行异步操作的存储调度?

时间:2017-02-15 17:39:16

标签: javascript redux react-redux

希望这并不算作一种意见"题。我正在关注this教程,此人在store.dispatch(loadCats())文件中调用src/index.js - 入口点。我有以下文件结构(与教程中的文件结构大致相同)。

.
├── README.md
├── package.json
├── public
│   ├── favicon.ico
│   └── index.html
└── src
    ├── actions
    │   ├── actionTypes.js
    │   └── partActions.js
    ├── api
    │   └── partApi.js
    ├── components
    │   ├── App
    │   │   ├── index.css
    │   │   ├── index.js
    │   │   └── index.test.js
    │   ├── Header
    │   │   └── index.js
    │   └── ThingCard
    │       ├── index.css
    │       └── index.js
    ├── containers
    │   └── ThingsGrid
    │       ├── index.css
    │       └── index.js
    ├── index.css
    ├── index.js
    ├── pages
    │   ├── DragonsPage
    │   │   └── index.js
    │   ├── ThingsPage
    │   │   └── index.js
    │   └── KittensPage
    │       └── index.js
    ├── reducers
    │   ├── initialState.js
    │   ├── partsReducer.js
    │   └── rootReducer.js
    ├── routes.js
    └── store
        └── configureStore.js

我有这些pages是容器的容器。换句话说,页面可以包含多个与某些逻辑类别相关的容器,例如ThingKittenDragon。我可以从每个store.dispatch(loadThings())调用page等函数。这是一种常见的模式还是我想念一些东西?

    // src/index.js
    const store = configureStore()
    store.dispatch(loadParts())

    ReactDOM.render(
        <Provider store={store}>
            <Router history={browserHistory} routes={routes}/>
        </Provider>,
      document.getElementById('root')
    );

这是我使用react-redux将商店传递到路线的方式。如果可以在我的page组件中分派操作,我将如何访问此商店?

1 个答案:

答案 0 :(得分:2)

因此,首先,要从“组件”页面访问您的商店,您可以使用mapStateToProps redux方法。通常将调度函数保留在reducer中,或者只创建action folder以在调用reducer开关之前执行操作。我没理解你为什么要访问这个商店文件夹。

import { connect } from 'react-redux'

class ExampleComponent extends Component {

  componentWillMount() {
    this.props.exampleAsyncFunction()
  }

  render() {
  return <p> 'anything' </p>
  }

}

const mapStateToProps = (state) => {
  return ({
    admin: state.admin,
  })
}

const mapDispatchToProps = (dispatch) => ({
  exampleAsyncFunction: reqObj => {
    dispatch(adminActions.exampleAsyncFunction())  
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ExampleComponent)