所以我设置了一个数据库,我试图从中提取信息并将其存储到状态数组中,以便我可以在网站上使用它。
这是我从数据库请求时得到的示例,为便于阅读而缩短
{
"count": 10,
"next": null,
"previous": null,
"results": [
{
"var1": "Test",
"var2": "",
"NeededInfo": "name1",
},
{
"var1": "Test",
"var2": "",
"NeededInfo": "name2",
}
]
}
所以我需要的是获取每个对象的 NeededInfo 并将其存储到一个数组中,以便我可以在 render() 上使用它。这就是我正在尝试的,但是当我执行 printToConsole()(未显示,只是一个 console.log(this.state))来查看状态数组的样子时,“其他”数组未定义
const title_URL = "http://123.456.789/namelist";
class Project extends Component {
constructor(props) {
super(props);
this.state = {
random1: "",
random2: "",
other: [],
items: []
}
}
componentDidMount() {
fetch(title_URL)
.then(response => {
return response.json();
})
.then(data => {
this.setState({
other: data.results.NeededInfo
})
});
}
我需要“其他”数组看起来像
other: ["name1", "name2"]
因为在我的 render() 中,我必须列出站点从数据库中提取的名称,以便用户可以看到所列项目的名称并用它做一些其他事情,然后我可以将其保存到“items”数组,以新的顺序排列,但如果我有一个预设的“其他”数组,那部分就可以使用。
最佳答案
您需要从结果中获取 NeededInfo
并将其插入临时数组(仅存储 NeededInfo
值),然后将其设置为状态。例如:
componentDidMount() {
fetch(title_URL)
.then(response => {
return response.json();
})
.then(data => {
// Here you need to use an temporary array to store NeededInfo only
let tmpArray = []
for (var i = 0; i < data.results.length; i++) {
tmpArray.push(data.results[i].NeededInfo)
}
this.setState({
other: tmpArray
})
});
}
关于javascript - 如何将来自 json API 响应的数据存储到 ReactJS 中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56783262/