我正在尝试在React中创建以下结构
{
items:
{Dogs: [{name: "Snoopy"}, {name: "Lola"}, {name: "Sprinkles"}],
Cats: [{name: "Felidae"}, {name: "Garfiled"}, {name: "Cat in the Hat"}]
}
使用以下功能:
handleAddItem(s) {
var key = Object.keys(s)[0];
var value = s[key];
var allItems = {...this.state.items};
allItems[key] = allItems[key];
allItems[key].push({name: value});
var ourItems = {};
ourItems = allItems[key];
ourItems.push({name: value });
// console.log(ourItems);
// console.log(allItems);
this.setState({items: allItems});
}
为什么键值对被添加到状态两次?
答案 0 :(得分:2)
将您的handleAddItem
修改为以下内容。
您的方法缺少Object.keys(s)[0]
。 Object.keys将返回一个数组,以便您获取确切的密钥,并假设它始终是一个单个密钥对象,您需要访问第零个索引。
同样在React中不要尝试改变状态变量,总是使用...
或其他深度克隆技术创建数组或对象变量的深层副本。
handleAddItem(s) {
//s comes in as an object key/value pair e.g. Dogs: Blackie
// Your expected key is at the 0th index
var key = Object.keys(s)[0];
var value = s[key];
// Cloning to prevent state mutations
var allItems = {...this.state.items};
var allItems[key] = allItems[key] || [];
allItems[key].push({name: value });
this.setState({items: allItems});
}
答案 1 :(得分:1)
如果给你一个动态密钥,那么你可以用括号引用一个对象密钥:
myObj['myKey'] = 'myValue'
您可以使用扩展语法添加数组和对象:
const myNewDogs = [{
name: 'new dog 1'
}, {
name: 'new dog 2'
}];
const myNewCat = {
name: 'new cat'
};
const items = {
dogs: [{
name: 'dog 1'
},
{
name: 'dog 2'
},
{
name: 'dog 3'
}
],
cats: [{
name: 'cat 1'
},
{
name: 'cat 2'
},
{
name: 'cat 3'
}
]
};
items['dogs'] = [...items['dogs'], ...myNewDogs];
items['cats'] = [...items['cats'], {...myNewCat}];
console.log(items);
请注意,对象扩展语法是提案but already on stage 3,即safe to use
答案 2 :(得分:0)
编辑请注意,您的问题中的示例并不是一个有效的JS对象,因为您有一些不匹配的括号。
如果你的结构看起来像这样。
const object = {
items: {
dogs: [],
cats: []
}
}
要附加到嵌套狗数组,您可以执行以下操作:object.items.dogs.push({ name: "Snoopy" })