使用异步路由时将 props 传递给组件

Posted

技术标签:

【中文标题】使用异步路由时将 props 传递给组件【英文标题】:Passing props to components when using async routing 【发布时间】: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 存储中设置值,但我仍然看不到这些道具是如何传递的。

【问题讨论】:

【参考方案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);

【讨论】:

以上是关于使用异步路由时将 props 传递给组件的主要内容,如果未能解决你的问题,请参考以下文章

映射到命名空间模块时将 prop 作为模块名称传递

详解vue父组件传递props异步数据到子组件的问题

如何使用反应路由器将道具传递给非子组件?

反应路由器和 this.props.children - 如何将状态传递给 this.props.children

在 React 路由器 5 中使用变量(不是静态组件)将道具传递给组件

React react-router-dom 将 props 传递给组件