在React + React-Router应用程序中保持状态的位置?

时间:2016-10-15 22:03:54

标签: reactjs react-router

我使用的是React-Router,但我不确定如何保持组件外的状态,同时如果该状态发生变化,组件仍会更新。我将属性传递给路径中的组件:

class Index extends React.Component { 
  constructor(props) {
    super(props);
    this.state = {foo: this.props.route.foo}
  }
}

var bar = 'bla'

var routes = (
  <Route path="/" foo=bar component={Index}/>
);

我的路由是在组件之外定义的,因此在上面的示例中更新bar并不会更新我的组件(也不会重绘)。解决这个问题的方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以使用componentWillReceiveProps。将新props传递给该组件时,将调用此方法。使用此功能,在收到新道具时设置新的state

以下情况应该有效。

class Index extends React.Component { 
  constructor(props) {
    super(props);
    this.state = {foo: this.props.route.foo}
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      foo: nextProps.route.foo,
    })
  }
}

var bar = 'bla'

var routes = (
  <Route path="/" foo={bar} component={Index}/>
);
相关问题