[英]reload / re-render the page if the parameters of the url change - react
我正在构建一个社交网络网络应用程序,因此我有多个不同的用户及其个人资料。 我的 App.js 文件中的 Switch 中有一个“/profile/:userId”的路由(显然也在我的后端)。 我的导航栏上还有一个 NavLink 按钮,用于转到我的个人资料。 用户还可以按某人帖子的用户名并转到他们的个人资料。 所有这些都很好,但有一个问题。 当我在用户的个人资料(不是我的个人资料)中并单击导航栏中的“我的个人资料”按钮时,即使路线发生变化(即如果我是用户 user1 并且我正在观看随机个人资料“/profile/user2”然后从我的导航栏中按下配置文件按钮,我转到路由“/profile/user1”,但页面不会重新呈现,所以我仍在观看用户的“user2”配置文件)。 所以我想在 url 的参数发生变化时触发重新加载。 或者至少那是我的想法。 如果您对何时重新加载/重新呈现页面有更好的想法,请与我分享。 顺便说一句,我对反应很陌生,所以请耐心等待:D
我不知道我的代码的哪一部分应该连同我的问题一起上传以提供帮助,所以如果您需要我的代码的任何部分,请告诉我,我会上传它。 我的导航栏上的“个人资料”按钮以及帖子中任何用户的用户名都是 Navlink。
来自我的 Post.js(负责我呈现的每个帖子的文件)的 Navlink(这是上传帖子的用户的“用户名”):
<div className="Post-user-nickname">
<NavLink className='Nav-link' to={'/profile/' + this.props.creator._id} user={this.props.creator}>{this.props.author}</NavLink>
</div>
我的导航栏中的 Navlink:
item = { id: 'Profile', text: 'Profile', link: '/profile/' + this.props.userId, auth: true }
<NavLink to={item.link} exact onClick={this.props.onChoose}>
{item.text}
</NavLink>
编辑:我的 Profile.js componentDidMount:
componentDidMount() {
const userId = this.props.match.params.userId;
this.setState({userIdNew: userId});
console.log('-------------------- ' + userId);
fetch('http://localhost:8080/feed/profile/' + userId, {
headers: {
Authorization: 'Bearer ' + this.props.token
}
})
.then(res => {
if (res.status !== 200) {
throw new Error('Failed to fetch user status.');
}
return res.json();
})
.then(resData => {
this.setState({ status: resData.status, user: resData.user });
console.log('prwtos: ' + this.state.user._id);
this.setState({
posts: resData.user.posts.map(post => {
return {
...post
};
})
});
this.setState({ imagePath: 'http://localhost:8080/' + resData.user.posts.map(post => {
let imgUrl = post.imageUrl;
return imgUrl;
})
});
this.setState({ userImage: 'http://localhost:8080/' + resData.user.image })
})
.catch(this.catchError);
this.loadPosts();
this.loadFollowers();
this.loadFollowing();
const socket = openSocket('http://localhost:8080');
socket.on('posts', data => {
if (data.action === 'create') {
this.addPost(data.post);
} else if (data.action === 'update') {
this.updatePost(data.post);
} else if (data.action === 'delete') {
this.loadPosts();
}
});
this.setState({userIdNew: userId});
}
基本上,当加载组件(页面)时,您正在componentDidMount
中执行请求,转到另一个配置文件并不意味着更改页面,您正在更改道具但请求永远不会重新加载,您可以
fetchUser
,这将使用this.props.match.params.userId
在componentDidMount
中:
fetchUser
在componentDidUpdate
中:
fetchUser
以获取新的用户数据并重新触发新的渲染
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.