首页 > 解决方案 > 如果 url 的参数发生变化,则重新加载/重新渲染页面 - 反应

问题描述

我正在构建一个社交网络网络应用程序,因此我有多个不同的用户及其个人资料。我在我的 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>

我导航栏中的导航链接:

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 组件DidMount:

  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});
  }

标签: javascriptreactjsreact-native

解决方案


基本上,您在componentDidMount加载组件(页面)时执行请求,转到另一个配置文件并不意味着更改页面,您正在更改道具但永远不会重新加载请求,您可以

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

    • 称呼fetchUser
    • 将当前用户 ID 保存在状态中
  • componentDidUpdate

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

推荐阅读