【问题标题】:Passing props to components when using async routing使用异步路由时将 props 传递给组件
【发布时间】:2017-08-01 12:01:42
【问题描述】:

我正在使用 react-boilerplate,它在 route.js 中使用异步调用来提供组件。

在'/'路径中加载的组件定义为:

const SPoints = ({ actions, loading, error, regions, selectedRegion, region, regionLoading }) => {

并且组件填充了来自这些的值,例如region.name 等

路由代码是:

常量 getRootComponent = (nextState, cb) => { 导入('容器/应用程序') .then(加载模块(cb)) .catch(errorLoading); } 导出默认函数 createRoutes(store) { // 使用 getAsyncInjectors 工厂创建可重用的异步注入器 const { injectReducer, injectSagas } = getAsyncInjectors(store); 返回 [{ 小路: '/', 名称:'点', 获取组件(下一个状态,CB){ getRootComponent(nextState, cb); }, 索引路由:{ 获取组件(下一个状态,CB){ 常量 importModules = Promise.all([ 导入('容器/SPoints/reducer'), 导入('容器/SPoints/sagas'), 进口('容器/点'), ]); 常量 renderRoute = loadModule(cb); importModules.then(([reducer, sagas, component]) => { injectReducer('spoints', reducer.default); 注入Sagas(sagas.default); 渲染路由(组件); }); importModules.catch(errorLoading); } } }

SPoints 收到的 props 是如何传递给它的?我在代码中看不到任何东西表明组件如何获得它的道具......

嗯。我现在认为正在导入的 sagas.js 是在 redux 存储中设置值,但我仍然看不到这些道具是如何传递的。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    简而言之,react-redux 中的 connect 高阶组件提供了来自 redux 存储区的这些道具。

    但是,路由器指向的组件将被注入一些来自 react-router 的 props。

    这里是 react-boilerplate 的示例容器之一。请注意底部的 connect 函数与 mapStateToPropsmapDispatchToProps 完全一样:将状态和调度操作映射到正在连接的组件上的 props [到 redux 的 store]。

    https://github.com/react-boilerplate/react-boilerplate/blob/master/app/containers/HomePage/index.js#L121

    export function mapDispatchToProps(dispatch) {
      return {
        onChangeUsername: (evt) => dispatch(changeUsername(evt.target.value)),
        onSubmitForm: (evt) => {
          if (evt !== undefined && evt.preventDefault) evt.preventDefault();
          dispatch(loadRepos());
        },
      };
    }
    
    const mapStateToProps = createStructuredSelector({
      repos: makeSelectRepos(),
      username: makeSelectUsername(),
      loading: makeSelectLoading(),
      error: makeSelectError(),
    });
    
    // Wrap the component to inject dispatch and state into it
    export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
    

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 1970-01-01
      • 2019-06-20
      • 2017-10-14
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2020-04-02
      相关资源
      最近更新 更多