gpt4 book ai didi

javascript - 从嵌套数组中获取 1 个数组并存储到 React 状态

转载 作者:行者123 更新时间:2023-12-03 02:15:17 26 4
gpt4 key购买 nike

这里是新的 React 爱好者,需要一点帮助。

所以我有这组数组存储在一个名为项目的状态

0:{id: 1, title: "Business Web", category: "Web Design", deleted_at: "0000-00-00 00:00:00"}
1:{id: 2, title: "Social App", category: "Mobile Development", deleted_at: "0000-00-00 00:00:00"}
2:{id: 3, title: "Ecommerce", category: "Web Development", deleted_at: "0000-00-00 00:00:00"}
3:{id: 4, title: "1", category: "1", deleted_at: "0000-00-00 00:00:00"}
4:{id: 5, title: "123123", category: "123123", deleted_at: "0000-00-00 00:00:00"}
5:{id: 6, title: "new", category: "new", deleted_at: "0000-00-00 00:00:00"}
6:{id: 7, title: "sdasd", category: "sdawd", deleted_at: "0000-00-00 00:00:00"}
7:{id: 8, title: "sssss", category: "ssssss", deleted_at: "0000-00-00 00:00:00"}
8:{id: 9, title: "Irene", category: "Bae", deleted_at: "0000-00-00 00:00:00"}
9:{id: 10, title: "sssss", category: "sssss", deleted_at: "0000-00-00 00:00:00"}

我使用它来将项目存储到名为 projectItem 的状态

this.setState({
projectItem: this.state.projects.filter(p => p.id === id)
})

这给了我这样的结果..

0: {id: 1, title: "Business Web", category: "Web Design", deleted_at: "0000-00-00 00:00:00"}

现在,当我尝试访问此状态并将其设置为输入的初始值时,它不起作用。我这样设置值

value={this.state.projectItem.title}

你能帮我看看我哪里出了问题吗?或者我这样做的方式不对?预先感谢您。

最佳答案

Array.prototype.filter返回一个数组,因此要获取一个项目,您可以执行类似的操作

cont filtered = this.state.projects.filter(p => p.id === id);
this.setState({
projectItem: filtered.length ? filtered[0] : null
});

也许你想find项目代替:

this.setState({
projectItem: this.state.projects.find(p => p.id === id);
});

关于javascript - 从嵌套数组中获取 1 个数组并存储到 React 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49393872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com