如何将props传递给react-router 1.0组件?

时间:2015-07-03 15:48:33

标签: reactjs react-router

请注意,虽然问题本身与this大致相同,但它涉及支持此版本的不同版本。关联的问题已经接受旧版本的答案

我对预期的工作流程非常困惑。

假设我有一个菜单系统,点击每个项目使用react-router导航到从服务器提取一些数据的区域。

url: yoursite/#/lists/countries
----------------------------
Billing Codes | <<Countries>> | Inventory Types 
---------------------------------------------------------
Countries:
---------------
Afghanistan
Azerbaijan
Belarus

有类似

的路线
Route #/lists component: Lists
   Route billing-codes component: BillingCodes
   Route countries component: Countries
   Route inventory-types component: InventoryTypes

我不希望在导航区域之前从服务器预加载数据,所以在我Countries组件的componentWillMount上我发射一个事件(我正在使用反流但是...无论如何)触发商店执行ajax请求并使用当前的国家/地区列表更新自己。

现在,Countries组件通过更新其道具中的国家/地区来对状态更改做出反应。除了 - 合理 - 因为我不应该在子组件上更新道具而产生不变的错误,我应该在顶层更新它。但最高级别是路由器本身,所以现在我只是丢失了 - 我应该听取更改并更新道具?

Cross-posted to the issue tracker因为我认为需要更清晰的文档)

2 个答案:

答案 0 :(得分:3)

阅读react-router 0.13 -> 1.0 Upgrade Guidethis example让我了解到以下内容:

{ this.props.children && 
     React.cloneElement(this.props.children, {newprop: this.state.someobject }) }

我们不是直接包含子组件,而是克隆它们并注入新属性。 (守护程序处理没有​​要呈现的子组件的情况。)现在,当子组件呈现时,它可以在this.props.newprop访问所需的属性。

答案 1 :(得分:1)

简单的方法是使用this.state,但如果您绝对必须使用this.props,那么您应该扩展Router.createElement

首先将createElement道具添加到Router渲染。

React.render(
  <Router history={history} children={Routes} createElement={createElement} />,
  document.getElementById('app')
);

将所有组件包装到新的Container组件中。

function createElement(Component, props) {
    return <Container component={Component} routerProps={props} />;
}

您的Container组件可能看起来像这样。将onLoadData功能传递给您的组件。

import React from 'react';
import _ from 'lodash';

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = { props: props.routerProps };
  }

  onLoadData(props) {
    var mergedProps = _.merge(this.state.props, props);
    this.setState({ props: mergedProps });
  }

  render() {
    var Component = this.props.component;
    return <Component {...this.state.props} onLoadData={this.onLoadData.bind(this)} />;
  }
}

然后,从您加载的组件中,当您从服务器获取数据时,只需触发this.props.onLoadData(data),数据将与您当前的道具合并。

Read the Router.createElement Documentation