【发布时间】:2021-04-29 11:07:05
【问题描述】:
我正在尝试使用 useEffect 更新组件中的状态
useEffect(() => {
async function fetchData() {
let response = await getAccountCoverTypes();
setData(response);
}
fetchData();
}, []);
我正在设置我的默认值:
const [data, setData] = useState({
payload: { title: "", accountCoverTypes: [] },
并试图通过数据映射
const {
payload: { title, accountCoverTypes },
} = data;
{accountCoverTypes.map((button, index) => (
...
))}
当我尝试使用数据时 - 我收到错误,无法读取未定义的属性标题。如何从useEffect 更新状态?
我的服务电话:
const call = async () => {
try {
const response = await getItem(xxx);
return response
}
json 返回:
{
"payload": {
"title": "text here",
"accountCoverTypes": [
{
"title": "sample text",
"details": "sample text",
"link": "test"
},..
]
}
}
【问题讨论】:
-
我不认为这段代码有什么问题,实际上我已经在codeandbox中重写了它并且它可以工作:codesandbox.io/s/gracious-williams-nts9y?file=/src/App.js
-
能否添加更多代码来查找问题
-
我添加了更多细节