【问题标题】:How to reset state in a component on prop change如何在道具更改时重置组件中的状态
【发布时间】:2019-12-15 11:33:16
【问题描述】:

我应该如何在每次道具更改时重置 Child 的状态?

父组件:

render() {
    const { show, month } = this.props; // January, February, ...

    return (
      { show ? <Child selectedMonth={month} /> : null }
    );
  }

子组件:

componentDidMount() {
    this.resetChildState();
    // this will never run if the Parent's month prop is changed
    // only if show becomes false from true
  }

我希望 resetChildState 在每个月更改时运行。

【问题讨论】:

  • 使用setState ("")

标签: reactjs


【解决方案1】:

尝试使用componentDidUpdate,在这个方法体中你可以比较来自parent的props是否改变了。因此,如果他们确实只是调用了您的重置方法或您想要的任何方法。 欲了解更多信息,请访问https://reactjs.org/docs/react-component.html#componentdidupdate

componentDidUpdate(prevProps, prevState) {
   if(this.props.selectedMonth!== prevProps.selectedMonth) {
        this.resetChildState();
   }
}

【讨论】:

    【解决方案2】:

    您可以使用getDerivedStateFromProps()

    static getDerivedStateFromProps(nextProps, prevState) {
     if(monthChanged){
      return initialState; //reset to initialState that you have defined.
      }
     return null;
    }
    

    【讨论】:

      【解决方案3】:

      如果您只想在更改道具后完全重置您的状态,您可以使用componentWillReceiveProps react 生命周期,如下所示:

      class Children extends React.Component {
          // ...
          state = {
            name: "test"
          };
      
          componentWillReceiveProps(nextProps) {
            this.setState({name: ""});
          }
          // ...
      }
      

      【讨论】:

        【解决方案4】:

        使用 ComponentDidUpdate

         componentDidUpdate() {
                if (this.props.id !== this.state.section_id) {
                    this.setState({
                        section_id:this.props.id,
                        filteredProducts:[],
                        productsByPage:[],
                        pageNumber:0,
                        hasMore:true,
                        showloading:true
        
                    },()=>this.fetchData());
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-14
          • 2023-03-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-21
          • 1970-01-01
          相关资源
          最近更新 更多