Reactjs 如何在嵌套管线内重置状态
我注意到,每次profile:id被更改为一个或另一个(/profile/1->profile/2),profile组件内部的状态都没有改变 当:id更改时,是否有办法“重置”组件状态?我很难弄明白这一点 我的代码看起来像这样Reactjs 如何在嵌套管线内重置状态,reactjs,Reactjs,我注意到,每次profile:id被更改为一个或另一个(/profile/1->profile/2),profile组件内部的状态都没有改变 当:id更改时,是否有办法“重置”组件状态?我很难弄明白这一点 我的代码看起来像这样 componentDidMount(){ document.addEventListener('scroll',this.trackScrolling); } 组件将卸载(){ document.removeEventListener('scroll',this.tra
componentDidMount(){
document.addEventListener('scroll',this.trackScrolling);
}
组件将卸载(){
document.removeEventListener('scroll',this.trackScrolling);
}
跟踪滚动=()=>{
const wrappedElement=document.getElementById('lastElement');
if(此.isBottom(wrappedElement)){
this.setState({render_count:this.state.render_count+1});
}
};
isBottom(el){
返回el.getBoundingClientRect()。请尝试以下操作:
- 使用props中的
match.params
从url获取id
- 使用
componentdiddupdate
更改组件的状态
componentDidUpdate(prevProps){
if(prevProps.match.params.id!==this.props.match.params.id){
这是我的国家({
渲染单元计数:0
})
}
}
我以前尝试过这个,但没有成功。如果键入console.log(this.state.render\u count)
在下面,您仍然可以获得上一个渲染计数。@James,状态更新是异步的,因此您将看到在渲染后更新的状态。然而,我在this.setState之后得到了另一个函数。当该函数运行时,它不会将渲染计数设置为0。您执行该函数的位置和方式(记录渲染计数)。还可以共享更多代码,建议…通常更新的状态将出现在下一个重新渲染周期中(因为状态更新为aysnc)。。
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;
}