Javascript React中的状态更改后,功能组件未重新呈现
我有一个功能组件,它在页面加载时从http请求检索数据,并使用useState更新状态以存储该数据。然后我尝试从数据映射出一个嵌套数组(polls.pollOptions),我得到一个错误:“TypeError:cannotreadproperty'map'of undefined”。如果我删除map函数并检查React组件扩展,我可以看到状态已更新,并且具有正确的数据。那么,为什么这个不呈现到屏幕上&为什么当数据要映射时会收到错误呢?这是我的组成部分:Javascript React中的状态更改后,功能组件未重新呈现,javascript,reactjs,react-hooks,use-effect,Javascript,Reactjs,React Hooks,Use Effect,我有一个功能组件,它在页面加载时从http请求检索数据,并使用useState更新状态以存储该数据。然后我尝试从数据映射出一个嵌套数组(polls.pollOptions),我得到一个错误:“TypeError:cannotreadproperty'map'of undefined”。如果我删除map函数并检查React组件扩展,我可以看到状态已更新,并且具有正确的数据。那么,为什么这个不呈现到屏幕上&为什么当数据要映射时会收到错误呢?这是我的组成部分: import React, { useS
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>
);
};
import React,{useState,useffect}来自“React”;
从“axios”导入axios;
从“react router”导入{useParams};
导出常量EditPolls2=()=>{
常量{u id}=useParams();
const[polls,setPolls]=useState([]);
useffect(()=>{
get(`/polls/${u id}`)。然后((p)=>{
setPolls(p.data);
});
},[u id]);
返回(
编辑投票2
{polls.pollpoptions.map((p)=>(
- {p.option}
))}
);
};
您当前的初始状态是空数组,您正在尝试访问pollOptions
,这是空数组中不存在的属性
如果您不需要任何东西,但pollOptions
,请将初始状态保留为空数组,在映射数据时使用polls
而不是polls.pollOptions
,并确保将pollOptions
设置为状态:
export const EditPolls2 = () => {
const { _id } = useParams();
const [polls, setPolls] = useState([]);
useEffect(() => {
axios.get(`/polls/${_id}`).then((p) => {
setPolls(p.data.pollOptions); // set the pollOptions array as the state
});
}, [_id]);
return (
<div>
<p>edit polls 2</p>
<div>
<ul>
{polls.map((p) => ( // use polls and not pollOptions
<li key={p.pollId}>{p.option}</li>
))}
</ul>
</div>
</div>
);
};
非常感谢。我确实需要检索整个对象,以便获取其他字段,如title、date等,但它的poll选项表明我得到了一个错误。可选链接是我所需要的。不客气:)
export const EditPolls2 = () => {
const { _id } = useParams();
const [polls, setPolls] = useState(); // no initial state
useEffect(() => {
axios.get(`/polls/${_id}`).then((p) => {
setPolls(p.data);
});
}, [_id]);
return (
<div>
<p>edit polls 2</p>
<div>
<ul>
{polls.pollOptions?.map((p) => ( // optional chaining
<li key={p.pollId}>{p.option}</li>
))}
</ul>
</div>
</div>
);
};