简体   繁体   English

如果 url 的参数发生变化,则重新加载/重新呈现页面 - 做出反应

[英]reload / re-render the page if the parameters of the url change - react

I am building a social network web app so i have multiple and different users and their profiles.我正在构建一个社交网络网络应用程序,因此我有多个不同的用户及其个人资料。 I have a route for "/profile/:userId" in my Switch in my App.js file (and also in my backend obviously).我的 App.js 文件中的 Switch 中有一个“/profile/:userId”的路由(显然也在我的后端)。 I also have a NavLink button on my navigation bar for going to my profile.我的导航栏上还有一个 NavLink 按钮,用于转到我的个人资料。 Users can also press on the username of someone's post and go to their profiles.用户还可以按某人帖子的用户名并转到他们的个人资料。 All that work great but with one problem.所有这些都很好,但有一个问题。 When i am in a user's profile (not my profile) and click on "my profile" button from my navigation bar, even though the route changes (ie if i am user user1 and i am watching a random profile "/profile/user2" and press the profile button from my navigation bar, i go to route "/profile/user1" but the page does not re-render so i am still watching user's "user2" profile).当我在用户的个人资料(不是我的个人资料)中并单击导航栏中的“我的个人资料”按钮时,即使路线发生变化(即如果我是用户 user1 并且我正在观看随机个人资料“/profile/user2”然后从我的导航栏中按下配置文件按钮,我转到路由“/profile/user1”,但页面不会重新呈现,所以我仍在观看用户的“user2”配置文件)。 So i want to trigger a reload if the parameters of the url change.所以我想在 url 的参数发生变化时触发重新加载。 Or at least that's what i though of.或者至少那是我的想法。 If you have a better idea of when to reload / re-render the page please share it with me.如果您对何时重新加载/重新呈现页面有更好的想法,请与我分享。 I am very new to react by the way so bear with me:D顺便说一句,我对反应很陌生,所以请耐心等待:D

I don't know exactly what part of my code i should upload along with my question to help so if you need any part of my code please tell me and i will upload it.我不知道我的代码的哪一部分应该连同我的问题一起上传以提供帮助,所以如果您需要我的代码的任何部分,请告诉我,我会上传它。 the "profile" button on my navigation bar and also the username of any user on a post are both a Navlink.我的导航栏上的“个人资料”按钮以及帖子中任何用户的用户名都是 Navlink。

the Navlink (which is the "username" of the user that uploaded the post) from my Post.js (the file responsible of every single post i am rendering):来自我的 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>

the Navlink in my navigation bar:我的导航栏中的 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>

edit: my Profile.js componentDidMount:编辑:我的 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});
  }

Basically, you are performing the request in componentDidMount when the component (the page) is loaded, going to another profile it doesn't mean change page, you are changing props but the request is never reloaded, you could基本上,当加载组件(页面)时,您正在componentDidMount中执行请求,转到另一个配置文件并不意味着更改页面,您正在更改道具但请求永远不会重新加载,您可以

  • Extract the request logic in another function that lives inside the component, something like fetchUser , this will use this.props.match.params.userId在组件内部的另一个函数中提取请求逻辑,比如fetchUser ,这将使用this.props.match.params.userId
  • In componentDidMount :componentDidMount中:

    • Call fetchUser调用fetchUser
    • Save current user id in state将当前用户 ID 保存在状态中
  • In componentDidUpdate :componentDidUpdate中:

    • You can check if the current user id in props is different from the one you saved in state (another profile is showed), if it is, you can call fetchUser again to obtain the new user data and retriggering a new render您可以检查 props 中的当前用户 id 是否与您保存在 state 中的不同(显示另一个配置文件),如果是,您可以再次调用fetchUser以获取新的用户数据并重新触发新的渲染

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM