我在React中有对象数组。我的问题是我不能获取数组的元素或长度。
以下是控制台中的图片:
我把它印成这样:
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);
}
})
取数结束后,我设置反应状态:
设置搜索结果(tempArray);
更新:
fetch(url)
.then(res => res.json())
.then(post => setSearchResult(post.results))
.catch(error => {
console.log(error);
});
};
setSearchResult是我之前定义的反应状态:
const [searchResult, setSearchResult] = useState([]);
现在它可以通过执行以下操作来获取我的searchResult数组的长度:
searchResult.length;