gpt4 book ai didi

javascript - 如果 url 的参数发生变化,则重新加载/重新渲染页面 - React

转载 作者:行者123 更新时间:2023-12-02 22:25:11 25 4
gpt4 key购买 nike

我正在构建一个社交网络网络应用程序,因此我有多个不同的用户及其个人资料。我的 App.js 文件(显然也在我的后端)的 Switch 中有一条“/profile/:userId”的路由。我的导航栏上还有一个 NavLink 按钮,用于转到我的个人资料。用户还可以按某人帖子的用户名并转到他们的个人资料。所有这些都很好用,但有一个问题。当我在用户的个人资料(不是我的个人资料)中并单击导航栏中的“我的个人资料”按钮时,即使路线发生变化(即,如果我是用户 user1 并且我正在观看随机个人资料“/profile/user2”并按导航栏中的个人资料按钮,我转到路由“/profile/user1”,但页面不会重新呈现,因此我仍在观看用户的“user2”个人资料)。所以我想在 url 的参数发生变化时触发重新加载。或者至少我是这么认为的。如果您对何时重新加载/重新渲染页面有更好的想法,请与我分享。顺便说一下,我的 react 很新,所以请耐心等待:D

我不知道我应该上传代码的哪一部分以及我的问题来提供帮助,因此如果您需要我的代码的任何部分,请告诉我,我会上传它。我的导航栏上的“个人资料”按钮以及帖子上任何用户的用户名都是导航链接。

来 self 的 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>

导航栏中的导航链接:

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 中执行请求,转到另一个配置文件并不意味着更改页面,您正在更改 Prop ,但请求永远不会重新加载,你可以

  • 在组件内部的另一个函数中提取请求逻辑,例如 fetchUser,这将使用 this.props.match.params.userId
  • componentDidMount中:

    • 调用fetchUser
    • 在状态中保存当前用户 ID
  • componentDidUpdate中:

    • 可以检查props中的当前用户id是否与state中保存的用户id不同(显示另一个配置文件),如果是,可以再次调用fetchUser来获取新用户数据并重新触发新的渲染

关于javascript - 如果 url 的参数发生变化,则重新加载/重新渲染页面 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59096245/

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