如何通过React_router传递状态?

这是引起我麻烦的文件:

var Routers = React.createClass({

  getInitialState: function(){
    return{
      userName: "",
      relatives: []
    }
  },

  userLoggedIn: function(userName, relatives){
    this.setState({
      userName: userName,
      relatives: relatives,
    })
  },

  render: function() {
    return (
      <Router history={browserHistory}>
        <Route path="/" userLoggedIn={this.userLoggedIn} component={LogIn}/>
        <Route path="feed" relatives={this.state.relatives} userName={this.state.userName} component={Feed}/>
      </Router>
    );
  }
});

我试图将新的this.state.relativesthis.state.userName通过路线传递到我的“提要”组件中。但我收到此错误消息:

警告:[反应路由器]您不能更改;它将被忽略

我知道为什么会这样,但是不知道我应该如何将状态传递给我的“ feed”组件。在过去的5个小时里,我一直在尝试解决此问题,我已变得非常绝望!

请帮忙!谢谢


解:

下面的答案是有帮助的,我要感谢athors,但是它们并不是最简单的方法。在我看来,最好的方法是:更改路线时,只需将一条消息附加到它上,如下所示:

browserHistory.push({pathname: '/pathname', state: {message: "hello, im a passed message!"}});

or if you do it through a link:

<Link 
    to={{ 
    pathname: '/pathname', 
    state: { message: 'hello, im a passed message!' } 
  }}/>

source: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

In the component you are trying to reach you can then access the variable like this for example:

  componentDidMount: function() {
    var recievedMessage = this.props.location.state.message
  },

I hope this helps! :)

蛋蛋猿2020/03/30 17:44:15

一旦安装了路由器组件,就无法更改React-router的状态。您可以编写自己的HTML5路由组件,并侦听网址更改。

class MyRouter extend React.component {
   constructor(props,context){
   super(props,context);
   this._registerHashEvent = this._registerHashEvent.bind(this)

 } 

 _registerHashEvent() {
    window.addEventListener("hashchange", this._hashHandler.bind(this), false);
  }
  ...
  ...

render(){
  return ( <div> <RouteComponent /> </div>)
}