使用反应钩子,为什么获取的数据未定义?
Using react hooks, why fetched data is undefined?
我还是新手,正在学习 React。
我遵循了教程,但我不断收到错误消息
'无法读取未定义的 属性 'name'' .
我在这里托管了我的代码:https://codesandbox.io/embed/sleepy-hellman-uf1h3
我不确定为什么这是未定义的,因为该对象可用。我可以在执行 console.log(mandatoryArticle)
时访问该对象
组件第一次渲染时mandatoryArticle[0]
不会设置。所以,你只需要稍微防御一下:
<h2 id="modal-title">mandatoryArticle[0] && mandatoryArticle[0].name}</h2>
您将 mandatoryArticle 设置为空数组,然后您正在访问该空数组中的 0 索引。您可能误解了 useEffect 钩子。它不是同步的。顺序设置为 mandatoryArticle => render => fetch => set articles => render.
我还是新手,正在学习 React。
我遵循了教程,但我不断收到错误消息
'无法读取未定义的 属性 'name'' .
我在这里托管了我的代码:https://codesandbox.io/embed/sleepy-hellman-uf1h3
我不确定为什么这是未定义的,因为该对象可用。我可以在执行 console.log(mandatoryArticle)
时访问该对象组件第一次渲染时mandatoryArticle[0]
不会设置。所以,你只需要稍微防御一下:
<h2 id="modal-title">mandatoryArticle[0] && mandatoryArticle[0].name}</h2>
您将 mandatoryArticle 设置为空数组,然后您正在访问该空数组中的 0 索引。您可能误解了 useEffect 钩子。它不是同步的。顺序设置为 mandatoryArticle => render => fetch => set articles => render.