首页 > 解决方案 > 如何在嵌套路由中进行状态重置

问题描述

我注意到每次 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;
}

标签: reactjs

解决方案


尝试以下操作:

  • match.params使用from props从 url 中获取 id
  • 用于componentDidUpdate改变组件的状态
componentDidUpdate(prevProps){
   if(prevProps.match.params.id !== this.props.match.params.id) {
     this.setState({
      render_count: 0
     })
   }
}

推荐阅读