如何重置包含所有可传递到达状态的反应组件? [英] How can I reset a react component including all transitively reachable state?

查看:17
本文介绍了如何重置包含所有可传递到达状态的反应组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶尔会有一些概念上有状态的 React 组件,我想重置这些组件.理想的行为相当于移除旧组件并读取新的原始组件.

React 提供了一个方法 setState ,它允许设置组件自己的显式状态,但不包括浏览器焦点和表单状态等隐式状态,也排除其子项的状态.捕捉所有这些间接状态可能是一项棘手的任务,我更愿意严格而彻底地解决它,而不是在每一个新的令人惊讶的状态下玩打地鼠.

是否有 API 或模式可以做到这一点?

我做了一个简单的例子来演示 this.replaceState(this.getInitialState()) 方法并将它与 this.setState(this.getInitialState()) 方法:jsfiddle - replaceState 是更健壮.

解决方案

为了确保你提到的隐式浏览器状态和 children 的状态被重置,你可以添加一个 key 属性;当它发生变化时,该组件将被丢弃并从头开始创建.

render: function() {//...return 

{孩子们}

;}

重置单个组件的本地状态没有捷径.

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 a new, pristine component.

React provides a method setState which allows setting the components own explicit state, but that excludes implicit state such as browser focus and form state, and it also excludes the state of its children. Catching all that indirect state can be a tricky task, and I'd prefer to solve it rigorously and completely rather that playing whack-a-mole with every new bit of surprising state.

Is there an API or pattern to do this?

Edit: I made a trivial example demonstrating the this.replaceState(this.getInitialState()) approach and contrasting it with the this.setState(this.getInitialState()) approach: jsfiddle - replaceState is more robust.

解决方案

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.

这篇关于如何重置包含所有可传递到达状态的反应组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆