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

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

提交回复
热议问题