【发布时间】:2021-07-25 08:21:51
【问题描述】:
我有一个功能组件,它在页面加载时从 http 请求中检索数据并更新状态以使用 useState 存储该数据。然后我尝试从数据中映射出一个嵌套数组 (polls.pollOptions),我收到一个错误:“TypeError: Cannot read property 'map' of undefined”。如果我删除 map 函数并检查 React 组件扩展,我可以看到状态已更新并且它具有正确的数据。那么为什么这不渲染到屏幕上,为什么当数据可以映射时收到错误呢?这是我的组件:
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useParams } from "react-router";
export const EditPolls2 = () => {
const { _id } = useParams();
const [polls, setPolls] = useState([]);
useEffect(() => {
axios.get(`/polls/${_id}`).then((p) => {
setPolls(p.data);
});
}, [_id]);
return (
<div>
<p>edit polls 2</p>
<div>
<ul>
{polls.pollOptions.map((p) => (
<li key={p.pollId}>{p.option}</li>
))}
</ul>
</div>
</div>
);
};
【问题讨论】:
标签: javascript reactjs react-hooks use-effect