A
A
Alex2021-02-20 21:33:51
React
Alex, 2021-02-20 21:33:51

How to update a component if only part of the url changes?

When you click on the user, NavLink changes the Url, and the Router redirects the user to the profile component, in which the id is retrieved from the URL using withRouter and a request is made to the server for the user's data, as a result we see the user's profile. When I click on the Profile link in the navbar (menu), NavLink substitutes my id in the URL, but the component does not rerender.
And the page of that user is still on the screen.
That is, when changing this url localhost:3000/profile/143 to localhost:3000/profile/54242 Router does not respond.
But if I refresh the page, an Ajax request occurs and my profile is displayed. How to make the component update itself (when the link is clicked)?

app.js:

<Route path={"/profile/:userId?"} render={() =>
    <ProfileContainer />} />

ProfileContainer
class ProfileContainer extends React.Component {

  componentDidMount() {
    console.log(this.props);
    // id из URL
    let userId = this.props.match.params.userId;
    console.log(userId);
    if(!userId) {
      if(this.props.isAuth) {
        console.log(this.props.isAuth);
        userId = this.props.authId;
      }
    }
    // запрос пользователя, по которому был клик
    axios.get(`https://social-network.samuraijs.com/api/1.0/profile/${userId}`)
      .then(response => {
        // здесь setUserProfile это колл бэк принадлежащий react-redux
        this.props.setUserProfile(response.data);
      });
  }
  
  
  
  render() {
    return (
      <Profile {...this.props} profile={this.props.profile} />
    )
  }
};

const mapStateToProps = (state) => ({
  profile: state.profilePage.profile,
  isAuth: state.auth.isAuth,
  authId: state.auth.userId
});

// withRouter добавляет данные из Url
let WithURLDataContainerComponent = withRouter(ProfileContainer);

export default connect(mapStateToProps, {setUserProfile})(WithURLDataContainerComponent);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valery, 2021-02-20
@Novichok45

Since the same component is rendered along this route, it is not unmounted from the dom when the url changes.
Therefore, you should add a method componentDidUpdatein which you will compare:

...
componentDidUpdate(prevProps) {
    if (prevProps.match.params.userId !== this.props.match.params.userId) {
        // шлете запрос с новым userId = nextProps.match.params.userId
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question