javascript - 为什么我们使用 this.initialState = this.state;
问题描述
谁能向我解释一下为什么要this.initialState
知道我在 React JS 中使用了类组件?
class Inscription extends Component {
constructor(props) {
super(props);
this.state = {
pseudo: '',
email: '',
password: '',
formErrors: {}
};
this.initialState = this.state;
}
解决方案
想象一下有一个包含多个输入的表单,最终用户提交了所有数据。成功提交后,您要重置表单中的所有内容。最简单的方法是这样做this.state = this.initialState
,您不需要定义 initialState 两次。
我不会将 initialState 添加到 Class 本身,而是在类之外定义它。
const initialState = {
pseudo: '',
email: '',
password: '',
formErrors: {}
};
class Inscription extends Component {
constructor(props) {
super(props);
this.state = initialState;
}
onSubmit(){
// do backend call
// some others events
// eventually reset the state
this.state = initialState;
}
}
推荐阅读
- java - Java中的递归数字排列
- matlab - 如何将 max() 结果的结果和索引应用于单行数组
- asp.net - 成功登录后,我重定向回登录页面 MVC 5
- reactjs - 如何处理来自另一个类的组件的 onChange 事件?
- oracle - 截断超过 2 个月的分区
- python - 指定对字符串列表进行排序的键
- r - 为什么我的输入和输出元素没有显示在 UI 中?
- python - 如何在按下按钮时清除 Kivy Core 图像以使小部件为空?
- tibco - tib:base64-to-string 在 tibco bw 6.3 中给出错误
- android - 当我将长时间运行的 Runnable 发布到主线程时,为什么它当时没有被阻塞?