![](/img/trans.png)
[英]How does react-router pass props to other components with <Links> and <Route>?
[英]Components gets the wrong props when clicking links in React-router
我正在一个简单的用户页面上,每个用户都有自己的个人资料。 配置文件页面在初始加载时起作用。
但是,如果我当前正在查看user1的配置文件,然后单击链接将我带到user2 ,则配置文件页面仍将加载user1,因为this.props.params
尚未更新。 如果我单击链接两次,则将显示user2的配置文件。 我需要帮助以使其正常工作
在这里,代码比单词更能说明问题:
var { Router, Route, Redirect, IndexRoute, IndexLink, Link, hashHistory, browserHistory } = ReactRouter;
var browserHistory = ReactRouter.browserHistory;
var Profile = React.createClass({
getInitialState: function() {
return {
userName: '',
userId: '',
displayName: ''
};
},
setProfile: function() {
$.post('/api/v1/rest/getUser', {username: this.props.params.name}, function (result) {
if(!result.error) {
this.setState({
userName: result.seo_name,
userId: result.member_id,
displayName: result.display_name
});
}
}.bind(this));
},
componentDidMount: function() {
this.setProfile();
},
componentWillReceiveProps: function() {
this.setProfile();
},
render: function() {
return (
<div>
{this.state.displayName}
</div>
);
}
});
var MainLayout = React.createClass({
render() {
return (
<div className="application">
<header>
{this.props.children.props.route.title}
</header>
<nav>
<Link to="/profile/user1">User 1</Link>
<Link to="/profile/user2">User 2</Link>
</nav>
{this.props.children}
</div>
)
}
});
ReactDOM.render((
<Router history={ReactRouter.browserHistory}>
<Route component={MainLayout}>
<Route name="profile" path="/profile/:name" title={'Viewing profile'} component={Profile} />
</Route>
</Router>
), document.getElementById('application'));
如您所见,我正在使用jquery进行ajax调用,并且在MainLayout组件的导航栏中添加了两个测试链接。 每次转到新的个人资料时,我都想重新运行ajax调用并立即获取新的个人资料信息。
另一个简短的问题:在MainLayout组件内,我正在使用Route元素( this.props.children.props.route.title
)上定义的道具在页眉中打印页面标题。 当前显示“正在查看个人资料”。 我希望它说“查看用户名的配置文件”,其中用户名是一个变量。 我想不出一个干净的反应方式来做到这一点(在父组件的标题后面添加一些内容)。
这里有两个建议:
解:
componentWillReceiveProps意味着将要设置新的道具。因此尚未设置。 但是nextProps可用。
componentDidMount: function() {
// use the name from props to get the profile
this.getProfile(this.props.params.name)
}
componentWillReceiveProps: function(nextProps) {
// use the name from nextProps to get the profile
this.getProfile(nextProps.params.name);
},
getProfile: function(name) {
// ajax call, use the *name* param
}
有一个名为Helmet的组件,它专门用于更改标题等内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.