【发布时间】:2021-05-15 22:13:52
【问题描述】:
`尝试更新 onClick 中的对象数组。我有两个状态,即数组格式的“initialValue”和“todos”。当我签入反应开发人员工具时,我可以看到有两种状态。任务的流程是用户可以在输入文本框中输入文本,一旦用户单击添加按钮,我希望将其添加为对象数组,我保留了一个布尔字段和 Id 字段。 我面临的问题是我可以正确获得“输入值”。我也得到了对象数组,但不是处于“待办事项”状态,并且值没有以数组格式更新,只有输入值发生了变化。例如: 0{completed:false, id:20, text:abc} 当我单击添加按钮时,数组没有更新为 1{completed:false, id:20, text:cde} ,而是在第 0 个postiton 本身的值正在更新。我在下面添加了代码任何人都可以帮助我实现输出。提前致谢。
class TodoForm extends Component {
constructor(props) {
super(props);
this.state = {
InputValue: "",
todos: [],
};
console.log("intialvalue", this.state.InputValue);
}
handleChange(e) {
this.setState({ InputValue: e.target.value });
}
handleSubmit(e) {
// alert("Form state value" + this.state.initalValue);
e.preventDefault();
this.setState([
...this.state.todos,
{
text: this.state.InputValue,
completed: false,
id: Math.random() * 1000,
},
]);
}
render() {
return (
<div className="Todo">
<form>
<input
type="text"
value={this.state.InputValue}
onChange={this.handleChange.bind(this)}
></input>
<button onClick={this.handleSubmit.bind(this)}>Add</button>
</form>
<p>{this.state.InputValue}</p>
</div>
);
}
}
export default TodoForm;
【问题讨论】:
-
感谢以上链接。是的,但上面链接的方法与我的略有不同。
标签: javascript arrays reactjs