【发布时间】:2020-06-08 10:26:05
【问题描述】:
我在 React 中有对象数组。我的问题是我不能获取数组的元素或长度。 这是控制台中的图片:
我认为 data.length 应该取数组的长度,不是吗?
我就是这样打印的:
console.log('array length:', searchResult.length);
console.log('array:', searchResult);
我怎么可能得到正确的数组但长度错误? 我的最终目标是在段落中显示数组元素,所以我需要有长度以及每个元素的值。
这就是我创建数组的方式:
fetch(url)
.then(res => res.json())
.then(post => {
const result = post.results;
for (let index = 0; index < result.length; index += 1) {
const obj = {
title: result[index].title,
rating: result[index].vote_average,
year: result[index].release_date.substr(0, 4),
};
tempArray.push(obj);
}
})
获取结束后我设置反应状态: setSearchResult(tempArray);
更新: 我通过消除 for 循环解决了我的问题。我一检索结果就将结果置于反应状态。像这样:
fetch(url)
.then(res => res.json())
.then(post => setSearchResult(post.results))
.catch(error => {
console.log(error);
});
};
setSearchResult 是我之前定义的反应状态:
const [searchResult, setSearchResult] = useState([]);
现在它可以通过以下方式获取我的 searchResult 数组的长度:
searchResult.length;
【问题讨论】:
-
只是出于好奇..
console.log(data[0])会输出第一个对象吗? -
不,未定义
-
那很奇怪,你能把
JSON.stringify(data)的输出贴出来吗? -
只有两个括号:[]
-
你为什么不使用 Array.map ?为什么你必须做这个非确认的过程?在函数式编程中很少使用 for 循环。