我是Java语言的新手,所以我可能缺少解决此问题的基础知识。我正在尝试不同的东西,正在阅读教程,但到目前为止还没有运气。
目标是修改状态,只需将新关键字添加到包含在“ blockOptions”对象内的数组“关键字”中即可。我添加一个键/值,然后使用.map()或在需要时删除关键字。我也在尝试使用ES6建议。
这里是构造函数:
blockOptions: {
...
keywords: [],
这是我从组件调用的功能
onAddKeyword(e) {
if (e.key === "Enter") {
var newKeyword = {
text: e.target.value,
key: Date.now()
};
this.setState({
blockOptions.keywords: [...this.state.blockOptions.keywords, newKeyword]
});
console.log(this.blockOptions.keywords);
e.target.value = "";
e.preventDefault();
}
}
如果我将相同的代码用于未嵌套在“ blockOptions”内部的数组,则一切正常。关于代码本身的任何建议都是有价值的,因为我还是JS新手。
感谢您的帮助
答案 0 :(得分:2)
The first issue in your code is that you supposse
{
blockOptions.keywords: []
}
works as a sort of shortcut for
{
blockOptions: {
keywords: []
}
}
The left-side on a literal object creation must be only a String
or a Symbol
, your example should throw an Uncaught SyntaxError: Unexpected token :
.
Besides that, you'll need to do something like:
this.setState({
blockOptions: {
...this.state.blockOptions, //copy all the properties
keywords: [...this.state.blockOptions.keywords, newKeyword]
}
})
The gather / ...
operator on Objects, is not an ES2015 feature, but its available through babel.
A native ES2015 alternative is
const blockOptionsCopy = Object.assign(
{},
this.state.blockOptions,
{ keywords: [...this.state.blockOptions.keywords, newKeyword] }
);
this.setState({
blockOptions: blockOptionsCopy
})
答案 1 :(得分:0)
const { blockOptions } = this.state;
blockOptions.keywords.push(newKeyword);
this.setState({ blockOptions });
答案 2 :(得分:0)
您必须不变地做并复制整个对象和内部数组。
首先使用传播运算符复制blockOptions
。然后使用新数组覆盖keywords
属性:
this.setState({
blockOptions: {
...this.state.blockOptions, // copy blockOptions
keywords: [...this.state.blockOptions.keywords, newKeyword] // overwrite keywords
}
});