How can I reset a react component including all transitively reachable state?

前端 未结 3 564
无人共我
无人共我 2020-12-02 10:37

I occasionally have react components that are conceptually stateful which I want to reset. The ideal behavior would be equivalent to removing the old component and readding

3条回答
  •  情书的邮戳
    2020-12-02 10:54

    Adding a key attribute to the element that you need to reinitialize, will reload it every time the props or state associate to the element change.

    key={new Date().getTime()}

    Here is an example:

    render() {
      const items = (this.props.resources) || [];
      const totalNumberOfItems = (this.props.resources.noOfItems) || 0;
    
      return (
        
    ); }

提交回复
热议问题