Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在道具更改时重置组件中的状态_Reactjs - Fatal编程技术网

Reactjs 如何在道具更改时重置组件中的状态

Reactjs 如何在道具更改时重置组件中的状态,reactjs,Reactjs,我应该如何在每次道具更改时重置孩子的状态 父组件: render() { const { show, month } = this.props; // January, February, ... return ( { show ? <Child selectedMonth={month} /> : null } ); } componentDidMount() { this.resetChildState(); // th

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

父组件:

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在每个月的更改上运行。

只要尝试使用componentDidUpdate,在该方法的主体中,您可以比较来自父级的道具是否更改。所以如果他们真的调用了你的重置方法或者你想要的任何方法。 欲了解更多信息,请访问


只需尝试使用componentDidUpdate,在该方法的主体中,您可以比较来自父级的道具是否更改。所以如果他们真的调用了你的重置方法或者你想要的任何方法。 欲了解更多信息,请访问

你可以用

静态GetDerivedStateFromPropsExtProps,prevState{ 伊夫蒙特改变了{ 返回initialState;//重置为您定义的initialState。 } 返回null; } 你可以用

静态GetDerivedStateFromPropsExtProps,prevState{ 伊夫蒙特改变了{ 返回initialState;//重置为您定义的initialState。 } 返回null; }
如果您想在更改道具后完全重置状态,可以使用组件WillReceiveProps react生命周期,如下所示:

类子类扩展React.Component{ // ... 状态={ 名称:测试 }; 组件将接收props外部props{ this.setState{name:}; } // ... }
如果您想在更改道具后完全重置状态,可以使用组件WillReceiveProps react生命周期,如下所示:

类子类扩展React.Component{ // ... 状态={ 名称:测试 }; 组件将接收props外部props{ this.setState{name:}; } // ... } 使用组件更新

使用组件更新

使用设置状态使用设置状态
componentDidUpdate(prevProps, prevState) {
   if(this.props.selectedMonth!== prevProps.selectedMonth) {
        this.resetChildState();
   }
}
 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());
        }
    }