gpt4 book ai didi

javascript - 单击 React-router 中的链接时,组件获得错误的 props

转载 作者:行者123 更新时间:2023-12-03 06:21:54 27 4
gpt4 key购买 nike

我正在开发一个简单的用户页面,其中每个用户都有自己的个人资料。个人资料页面在初始加载时工作。

但是,如果我当前正在查看 user1 的个人资料,然后点击链接转到 user2,个人资料页面仍会加载 user1 em> 因为 this.props.params 尚未更新。如果我点击链接两次,就会显示user2的个人资料。我需要帮助才能使其正常工作

在这里,代码胜于 Eloquent :

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 元素上定义的 props 打印页眉中的页面标题 (this.props.children.props.route.title )。目前显示的是“查看个人资料”。我希望它说“查看用户名的个人资料”,其中用户名是一个变量。我无法找出一种干净的 react 方法来执行此操作(将某些内容附加到父组件的标题中)。

最佳答案

这里有两个建议:

  1. 将其命名为getProfile,而不是setProfile..
  2. getProfile 函数应该接受一个参数,而不是依赖于上下文;)

解决方案:

componentWillReceiveProps 表示将要设置新的 props.. 所以它们还没有设置。但是 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,专门用来改变title之类的东西

    https://github.com/nfl/react-helmet

    关于javascript - 单击 React-router 中的链接时,组件获得错误的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829031/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com