我正在尝试使用 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"
},..
]
}
}
答案 0 :(得分:0)
给你一个解决方案
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
let response = await getAccountCoverTypes();
setData(response);
}
fetchData();
}, []);
{
data &&
data.accountCoverTypes &&
data.accountCoverTypes.length &&
data.accountCoverTypes.map((button, index) => (
...
))}
在循环或迭代数据变量之前,您应该检查数据是否存在。
答案 1 :(得分:0)
好的,当您的函数第一次执行时,数据值将是未定义的,因为您没有为该状态设置任何初始值 const [data, setData] = useState()//initial value is not set;
在使用从 useEffect 挂钩调用的 setData 函数更新数据的意义上,您的方法是绝对正确的。一旦你的异步函数执行 - 数据将被更新并且组件将被重新渲染
答案 2 :(得分:-1)
React 依赖于 Hooks 的调用顺序。https://reactjs.org/docs/hooks-rules.html 这意味着在 useEffect 运行后,useState 重新初始化数据
因此将 useState 移动到代码中的 useEffect 之前
const [data, setData] = useState();
useEffect(() => {
async function fetchData() {
let response = await getAccountCoverTypes();
setData(response);
}
fetchData();
}, []);