Answer the question
In order to leave comments, you need to log in
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 />} />
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
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 componentDidUpdate
in 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 questionAsk a Question
731 491 924 answers to any question