【发布时间】:2021-12-11 03:09:00
【问题描述】:
我照常从外部 API 获取数据,这是我的典型做法:
获取 API:
const [tshirts, setTshirts] = useState([]);
const fetchData = () => {
fetch('apiEndpoint')
.then((response) => response.json())
.then((data) => {
setTshirts(data[0].clothes.regular.top); // path to my array
})
.catch((error) => {
console.log(error);
});
};
React.useEffect(() => {
fetchData();
}, []);
通过数组映射:
const tshirtArray = tshirts.tShirt; // specifying the path
const listItems = tshirtArray.map((item) => <li>{item}</li>);
<ul>{listItems}</ul>
数据结构示例:
[
{
id: 1,
clothes: {
regular: {
top: {
sleeveless: [],
tShirt: [
"image-path-here"
],
.....
.....
.....
当我第一次执行代码时,它可以工作,但一段时间后或刷新页面后,我收到错误 TypeError: Cannot read properties of undefined (reading 'map')
为什么没有定义?路径是正确的,获取数组也应该是正确的。找不到它不工作的原因。
【问题讨论】:
-
tshirts 最初是数组,所以不能取
tshirts.tShirt -
@sojin 但我还能如何从数组中获取项目
-
你删除了另一个问题,所以我在这里评论:你有
<Component />,即根本没有传递任何道具。
标签: javascript arrays reactjs react-hooks fetch