[英]In ReactJS todo app I am trying to set input field text state into another state which is array of objects
我正在做简单的待办事项应用程序。 我有 1 个输入框和添加按钮。 在输入框中键入并单击添加按钮时,文本将显示在下面的列表中。 我正在使用以下构造函数:
class Entry extends Component {
constructor() {
super()
this.state = {
st_search_field: '',
st_lists: [
{
list_id: new Date(`enter code here`),
list_name: ''
}
]
}
}
现在我创建list_handler = () => {...... }
function 将 search_field 文本设置为 list_name 值。 我在 onClick 期间使用 list_handler 方法添加按钮。 I have started by using const join = Object.assign({}, this.state)
in list_handler function and tried using this.setState({st_lists.list_name: this.state.st_searh_field})
but st_lists.list_name
is marked in red in VS 编辑器。 在 setState 方法上尝试了this.state.st_lists.map(li => {})
但即使这样也会出错。
您不能在状态子对象之一上设置 state 这样做:
const st_lists = this.state.st_lists;
st_lists.list_name = this.state.st_search_field;
this.setState({st_lists});
st_lists.list_name
不是键,需要添加合并 object
this.setState({
st_lists: [
{
...this.state.st_lists,
list_name: this.state.st_searh_field,
},
]
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.