我在表单中有三个输入字段,两个按钮添加问题并提交: 在前两个字段中,用户可以一次输入值,在第三个字段中,用户应能够通过单击添加问题,最后输入多个值或多个问题 当用户提交表单时,应该设置状态
<input type="text" name="intentName" />
<input type="text" name="Description" />
<input type="text" name="ques" />
state={
data:[
{"id":1,"intentName":"getPhoneNo","Description":"getting users phone no","ques":[{"q1":"how can i get users phone no"},{"q2":"give me phone number"}]},
]
}
我想设置状态并将项目添加到队列
例如:我想添加{"id":2,"intentName":"getWifi","Description":"getting users phone no","ques":[{"q1":"how can i get users wifi password"},{"q2":"give me wifi password"}]}
答案 0 :(得分:2)
向this.setState
传递回调以获取前一个data
并添加新对象,如:
data: [...prevState.data, obj]
摘要:
/*
const state = {
data: [
{
id: 1,
intentName: "getPhoneNo",
Description: "getting users phone no",
ques: [{ q1: "how can i get users phone no" }, { q2: "give me phone number" }]
}
]
};
*/
this.setState(prevState => {
const obj = {
id: 2,
intentName: "getWifi",
Description: "getting users phone no",
ques: [{ q1: "how can i get users wifi password" }, { q2: "give me wifi password" }]
};
return {
data: [...prevState.data, obj]
};
});