react-router:在没有Redux的路由之间共享状态

时间:2016-12-12 20:08:13

标签: reactjs react-router

我想在两个兄弟路线之间建立一个共享状态(远程提取的客户列表):TimesheetsClients
我想尝试用“纯粹的”React(No Flux架构)走多远。

此示例有效,但我有一个错误:browser.js:49 Warning: [react-router] You cannot change <Router routes>; it will be ignored 所以,它似乎不喜欢异步道具。

constructor(props) {
   super(props);
   this.state = {
      clients : []
   }
}

componentDidMount() {
   fetch("clients.json")
     .then(response => response.json()) 
     .then(clients => this.setState({ clients }));
}

render() {
  return (
    <Router history={browserHistory}>
      <Route path="/" component={Header} >
        <Route path="timesheet" component={() => (<Timesheets {...this.state} />) }/>
        <Route path="clients" component={() => (<Clients {...this.state} />) }/>
      </Route>
    </Router>
  );
}

是否可以向每条路线发送异步道具? 或者是否可以在父路由(Header组件)中设置整个状态,然后从每个子路由(TimesheetsClients组件)访问此状态?

2 个答案:

答案 0 :(得分:8)

您可以使用high-order component来获取并向顶级组件注入数据。然后,您可以通过const FetchHOC = url => Component => class extends React.Component() { state = { data: null }; componentDidMount() { fetch(url).then(data => this.setState({ data })); } render() { return <Component {...this.props} {...this.state.data} />; } } example here)将道具传递到子路线。

HOC

<Route path="/" component={FetchHOC('http://some-url')(App)}>
   <Route path="subroute1" component={SubRoute1} />
   <Route path="subroute2" component={SubRoute2} />
</Route>

路线配置

render()

父路线<div className="App"> {this.props.children && React.cloneElement(this.props.children, { data: this.props.data, // ... })} </div>

{{1}}

正如您在this fiddle中所看到的,我可以使用此技术将获取的数据传递到路径层次结构中。

答案 1 :(得分:2)

你可以看看反应情境。 Redux也使用Context。它允许您将一些数据传递给所有孩子。但是你应该编写代码来使用这些数据,例如你已经确定了contextTypes等。

您可以在docs上查看有关如何使用它的详细信息。