【发布时间】:2017-05-18 21:01:28
【问题描述】:
这是给我带来麻烦的文件:
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.relatives 和this.state.userName 传递到我的“feed”组件中。但我收到此错误消息:
警告:[react-router] 你不能改变;这将是 忽略
我知道为什么会发生这种情况,但不知道我应该如何将状态传递给我的“提要”组件。在过去的 5 个小时里,我一直在尝试解决这个问题,我变得非常绝望!
请帮忙! 谢谢
解决方案:
下面的答案很有帮助,我感谢作者,但他们不是最简单的方法。 在我的情况下,最好的方法是这样的: 当您更改路线时,您只需像这样附加一条消息:
browserHistory.push({pathname: '/pathname', state: {message: "hello, im a passed message!"}});
或者如果您通过链接进行操作:
<Link
to={{
pathname: '/pathname',
state: { message: 'hello, im a passed message!' }
}}/>
来源:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md
在您尝试访问的组件中,您可以像这样访问变量,例如:
componentDidMount: function() {
var recievedMessage = this.props.location.state.message
},
我希望这会有所帮助! :)
【问题讨论】:
-
查看此答案stackoverflow.com/a/29720488/444829
<Route>来自旧版本,因此您将继续使用component属性,而不是该答案使用的handler属性。 -
会写一个带有解释的答案。
-
nononono 不要!我已经找到了解决方案!我在找到解决方案后立即删除了我所做的评论,但不幸的是,你似乎已经把它变红了。非常感谢:)
-
@PaulS 再次想到我一直在努力学习,而我发现的解决方案似乎只是一个半解决方案。你介意解释一下你提到的解决方案在我的场景中会是什么样子吗?真的很棒! :)
-
随时将您更新的解决方案作为答案,然后将您的答案标记为正确答案。
标签: reactjs react-router browser-history