【发布时间】:2021-06-03 16:45:53
【问题描述】:
我一直在从事那个 React 项目,并且一直在使用 axios 从我的后端获取数据。我多次收到 (TypeError: Cannot read property 'map' of undefined) 错误,我尝试了多次修复,但没有希望修复。我添加了一个用于加载的钩子,以确保在渲染之前存在数据,但是如果我在页面之间返回和第四次,我会收到相同的错误
这是我的代码:
function Developer(props) {
const [data, setData] = useState();
const [loading , setLoading] = useState(true)
const [error, setError] = useState();
var id = props.match.params.id
var location = props.match.params.location
useEffect(() => {
axios(`http://localhost:5000/api/${location}/${id}`)
.then((response) => {
setData(response.data);
})
.catch((error) => {
console.error("Error fetching data: ", error);
setError(error);
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) return "Loading...";
if (error) return "Error!";
return (
<div>
<h1>{data.Developer}</h1>
<ul>
{
data.Projects.map((project) => (<li key = {project._id}>
<a href= {`/${location}/${id}/${project._id}`}>{project.Project}</a></li> ))
}
</ul>
</div>
)}
【问题讨论】:
-
data.Projects 未定义。我们能看到 api 调用的响应是什么样的吗?此外,您似乎没有在 api 调用之前将加载变量设置为 true。因此,您可能需要检查 jsx 中是否未定义数据。基本上看起来正在发生的是你试图循环一个未定义的变量,但你没有告诉视图等到数据被获取。加载变量将在 axios 调用之前为您 setLoading(true) 执行此操作。然后在 setData 之前 setLoading(false)。
-
data.Projects 是 axios 调用返回的集合的一部分,因此它存在。我真的不知道何时将加载变量设置为 true 以及何时设置为 false。你能解释一下吗
标签: javascript node.js reactjs