最近使用 react-router 来做单页面路由,现在遇到一个问题,就是对于同样的路由(不同的参数),指向同一个组件,改变参数的情况下,该组件不能卸载和重新挂载,功能效果类似于在用户a的主页(/users/1/overview),点击进入用户b的主页(/users/2/overview),这时候,组件没有被卸载。
// 路由配置
<Route path='/' component={App}>
<Route path='users/:userId/overview' component={User} />
</Route>
// 用户组件
export class User extends Component {
constructor() {
this.state = {
profile: {},
firends: [],
};
}
componentDidMount() {
const { userId } = this.props.params.userId;
this.loadProfile(userId);
this.loadFirends(userId);
}
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps.params.userId);// 修改url进入的,这里能正确获取到新用户id
return true;
}
loadProfile(userId) {
fetch();// 请求数据,更新state
}
loadFirends(userId) {
fetch();// 请求数据,更新state
}
render() {
const { profile, firends } = this.state;
return (
<div>
<div>profile data</div>
<div>firends data</div>
</div>
);
}
}
当我点击 /users/1/overview
进入用户a主页后,我修改浏览器地址为 /users/2/overview
回车(或者,我点击用户a界面上的 Link 标签进入 /users/2/overview
),这个时候,url是改变了,在 shouldComponentUpdate
函数中也能正确获取用户id,这个时候我如何巧妙的处理当前组件重新加载数据这个过程,我知道可以在 shouldComponentUpdate
函数中获取新的用户id来和 this.props.params.userId
做对比,不同则重新加载数据,但是我又很多这种组件啊,很多这种跳转,是不是我每一个组件都要这么处理啊,感觉要疯了。。而且,在复杂的页面里面,有可能在组件挂载的时候,我需要发送很多个请求,难道我在 componentDidMount
函数内部所做的处理也要在 shouldComponentUpdate
里面再来一次吗?
react-router 相关的资料我也看了七七八八,难免有遗漏的部分,还是很困惑,不知道如何解决类似的问题,所以才来提问,希望知道的朋友说说自己的解决方法,先谢谢了。