reactjs - 如何在嵌套路由中进行状态重置
问题描述
我注意到每次 profile:id 更改为一个和另一个(/profile/1 -> profile/2)时,配置文件组件内的状态都不会改变。
当 :id 更改时,有没有办法“重置”组件状态?我很难弄清楚这一点。
我的代码看起来像这样
<Route path ='/profile/:id/' component={ Profile } />
componentDidMount(){
document.addEventListener('scroll', this.trackScrolling);
}
componentWillUnmount(){
document.removeEventListener('scroll', this.trackScrolling);
}
trackScrolling = () => {
const wrappedElement = document.getElementById('lastElement');
if (this.isBottom(wrappedElement)) {
this.setState({render_count: this.state.render_count+1});
}
};
isBottom(el) {
return el.getBoundingClientRect().bottom <= window.innerHeight;
}
解决方案
尝试以下操作:
match.params
使用from props从 url 中获取 id- 用于
componentDidUpdate
改变组件的状态
componentDidUpdate(prevProps){
if(prevProps.match.params.id !== this.props.match.params.id) {
this.setState({
render_count: 0
})
}
}
推荐阅读
- spring - `[ctor-http-nio-x]` 在控制台/日志中表示什么
- docker - Bazel docker容器映像未复制文件
- singularity-container - 有没有办法跟踪像“docker ps”这样的奇点容器而不从奇点实例开始?
- apache-spark - 了解 Spark 创建的分区数量
- azure-devops - 如果 WIT 有不同的状态,如何在同一个 Sprints 页面 Taskboard 上有效地管理 Task 和 Bug 工作项?
- javascript - 如何使用 jsHint 提取 CLI 报告中的代码指标?
- flutter - Flutter IAP 未在 TestFlight 上显示
- node.js - Express 端点超时
- javascript - 添加事件侦听器以将按钮连接到函数
- apache-kafka - 如何配置 kafka 代理以快速保留?