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

Where should store dispatch for async actions be made in Redux?

希望这不算是一个 "opinion" 问题。我正在学习 this 教程,此人在他们的 src/index.js 文件中调用 store.dispatch(loadCats()) - 入口点。我有以下文件结构(与教程中的大致相同)。

.
├── 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。从每个 page 调用像 store.dispatch(loadThings()) 这样的函数对我来说是有意义的。这是一种常见的模式还是我想念某些东西?

    // 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 组件中分派操作,我将如何访问该商店?

因此,首先,要从您的组件页面访问您的商店,您可以使用 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)