![](/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.