我试图将新对象推入反应状态,但数组状态始终返回空。
这是我的反应状态:
this.state = {
formname: '',
newform : [],
formField: {},
formsCollection: []
};
来自状态的对象结果formField:
{0: {…}, 1: {…}, formname: "form 1"}
0: {type: "text", label: "First Name", title: "", name: "", uniquekey: "", …}
1: {type: "", label: "Last Name", title: "", name: "", uniquekey: "", …}
formname: "form 1"
__proto__: Object
}
更新状态的表单 onSubmit() 处理函数:
onSubmit= (e) =>
{
e.preventDefault();
const finalData = {formname: this.state.formname, ...this.state.newform};
let formField = Object.assign(this.state.formField, finalData);
this.setState({
formField
});
console.log(this.state.formField, 'single form field');
// const formsCollection = this.state.formsCollection.slice();
// if(formsCollection.length){
// this.setState({ formsCollection: formsCollection });
// }
// else{
// formsCollection.push(formField);
// this.setState({ formsCollection : formsCollection });
// }
this.setState((prevState) => ({
formsCollection: [...prevState.formsCollection, formField]
}));
console.log(this.state.formsCollection, 'forms collection are: ')
};
每次单击 onSubmit() 时,它都会将单个formField对象打印到控制台,但不会将新对象添加到formsCollection数组中。此外,我同时使用了 prevState 和 spread 运算符方法,但在这两种情况下,console.log(this.state.formsCollection, 'forms collection are: ')每次都向我打印一个空数组。
请帮助解决这个问题。
慕少森
青春有我
慕森王
相关分类