[英]Reactjs : TypeError: Cannot read property 'map' of undefined
我一直在研究那个 React 项目,并且一直在使用 axios 从我的后端获取数据。 我多次收到 (TypeError: Cannot read property 'map' of undefined) 错误,我尝试了多次修复,但没有希望修复。 我添加了一个用于加载的钩子以确保在渲染之前存在数据,但是如果我在页面之间返回和第四个 go 我收到相同的错误
这是我的代码:
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>
)}
在对其进行 map 之前,您应该检查数据属性的性质。
{
data && data.Projects.length !== 0 &&
data.Projects.map((project) => (<li key = {project._id}>
<a href= {`/${location}/${id}/${project._id}`}>{project.Project}</a></li> ))
}
我建议你使用 javascrip fetch
我自己多次遇到这个错误。
首先检查您从 api 获得的数据是否是 javascript 对象的数组
这是一个简单的解决方案。
{data ? data.Projects.map((project) => (<li key={project._id}>
<a href={`/${location}/${id}/${project._id}`}>{project.Project}</a></li>)) :<div>Loading..</div>}
所以我在这里所做的是使用三元运算符,它将检查数据 state 是否有数据,如果有它将显示数据,否则它将显示“正在加载...”
Axios 需要一些时间来获取和设置数据,但页面在此之前呈现,这就是为什么它显示无法读取未定义的属性“地图”
返回的数据可能不包含您需要的内容。
尝试打印出返回的数据
axios(`http://localhost:5000/api/${location}/${id}`)
.then((response) => {
console.log(response.data);
setData(response.data);
})
它可能是一个有效的响应,但不包含该变量data.Projects
。 如果您想处理该值的缺失,您可以使用以下内容:
(data.Projects || []).map(...)
这样,如果data.Projects
是假的,它将被一个空数组替换,它会调用[].map(...)
。
如前所述,您的 setLoading(true) 要求。
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(() => {
// ooh look, we are in a loading state here, cause the data hasn't come back from the server at this point.
setLoading(true);
axios(`http://localhost:5000/api/${location}/${id}`)
.then((response) => {
setData(response.data);
// awesome, data has returned from the server, we aren't loading anymore, but the finally block handles that scenario for us.
})
.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 && data.Projects.length && data.Projects.map((project) => (<li key = {project._id}>
<a href= {`/${location}/${id}/${project._id}`}>{project.Project}</a></li> ))
}
</ul>
</div>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.