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

前端 未结 3 476
无人共我
无人共我 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:38

    To ensure that the implicit browser state you mention and state of children is reset, you can add a key attribute to the root-level component returned by render; when it changes, that component will be thrown away and created from scratch.

    render: function() {
        // ...
        return <div key={uniqueId}>
            {children}
        </div>;
    }
    

    There's no shortcut to reset the individual component's local state.

    0 讨论(0)
  • 2020-12-02 10:51

    You should actually avoid replaceState and use setState instead.

    The docs say that replaceState "may be removed entirely in a future version of React." I think it will most definitely be removed because replaceState doesn't really jive with the philosophy of React. It facilitates making a React component begin to feel kinda swiss knife-y. This grates against the natural growth of a React component of becoming smaller, and more purpose-made.

    In React, if you have to err on generalization or specialization: aim for specialization. As a corollary, the state tree for your component should have a certain parsimony (it's fine to tastefully break this rule if you're scaffolding out a brand-spanking new product though).

    Anyway this is how you do it. Similar to Ben's (accepted) answer above, but like this:

    this.setState(this.getInitialState());
    

    Also (like Ben also said) in order to reset the "browser state" you need to remove that DOM node. Harness the power of the vdom and use a new key prop for that component. The new render will replace that component wholesale.

    Reference: https://facebook.github.io/react/docs/component-api.html#replacestate

    0 讨论(0)
  • 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 (
        <div className="items-container">
          <PaginationContainer
            key={new Date().getTime()}
            totalNumberOfItems={totalNumberOfItems}
            items={items}
            onPageChange={this.onPageChange}
          />
        </div>
      );
    }
    
    0 讨论(0)
提交回复
热议问题