如何将对象插入反应中的对象列表?
How to insert object into list of objects in react?
我有嵌套对象列表:
this.state = {
lst: [
{
id: "TKT4321",
subject: "abc",
reply: [
{ id: "TKT34343", subject: "axyz" },
]
},
{
id: "TKT34341",
subject: "aaaaa",
reply: [
{ id: "TKT322", subject: "abfjf" },
]
},
],
}
我想附加对象以回复 属性。例如
{
id: "TKT34341",
subject: "aaaaa",
reply: [
{ id: "TKT322", subject: "abfjf" },
{ id: "TK2222", subject: "jkjk" },
]
},
哪种方法最好?请帮助我。
如果你想改变状态,你可以像这样使用展开运算符...
:
this.setState((prevState) => {
const { lst } = prevState
return lst.map((elem) => ({
...elem,
reply: [ ...elem.reply, { id: "TK2222", subject: "jkjk" } ]
}))
})
我还没有尝试过,但是你可以从这个例子中得到灵感。
再见,这里是工作示例:
let lst = [
{
id: "TKT4321",
subject: "abc",
reply: [
{ id: "TKT34343", subject: "axyz" },
]
},
{
id: "TKT34341",
subject: "aaaaa",
reply: [
{ id: "TKT322", subject: "abfjf" },
]
},
];
let result = lst.map(el => {
if (el.id === "TKT34341"){
el.reply.push({ id: "TK2222", subject: "jkjk" });
}
return el;
});
console.log(result);
然后如果你想将result
存储到状态中,只需调用this.setState({lst : result});
我有嵌套对象列表:
this.state = {
lst: [
{
id: "TKT4321",
subject: "abc",
reply: [
{ id: "TKT34343", subject: "axyz" },
]
},
{
id: "TKT34341",
subject: "aaaaa",
reply: [
{ id: "TKT322", subject: "abfjf" },
]
},
],
}
我想附加对象以回复 属性。例如
{
id: "TKT34341",
subject: "aaaaa",
reply: [
{ id: "TKT322", subject: "abfjf" },
{ id: "TK2222", subject: "jkjk" },
]
},
哪种方法最好?请帮助我。
如果你想改变状态,你可以像这样使用展开运算符...
:
this.setState((prevState) => {
const { lst } = prevState
return lst.map((elem) => ({
...elem,
reply: [ ...elem.reply, { id: "TK2222", subject: "jkjk" } ]
}))
})
我还没有尝试过,但是你可以从这个例子中得到灵感。
再见,这里是工作示例:
let lst = [
{
id: "TKT4321",
subject: "abc",
reply: [
{ id: "TKT34343", subject: "axyz" },
]
},
{
id: "TKT34341",
subject: "aaaaa",
reply: [
{ id: "TKT322", subject: "abfjf" },
]
},
];
let result = lst.map(el => {
if (el.id === "TKT34341"){
el.reply.push({ id: "TK2222", subject: "jkjk" });
}
return el;
});
console.log(result);
然后如果你想将result
存储到状态中,只需调用this.setState({lst : result});