useEffect 中的 API 调用返回未定义
我有一个简单的功能组件,其中包括获取本地存储的 JSON 文件。
我试图从 JSON 文件中引入数据,虽然这应该是一个简单的任务,但我遇到了一个问题。
我的控制台日志显示两个单独的日志 - 一个是空对象,可能来自 useState 定义,第二个包含来自其中的 fetch 的数据。
因此,当我尝试对正在获取的数据执行任何操作时,将返回 undefined
,因此我无法使用它。我觉得我错过了一些明显的东西,但我不完全确定这里发生了什么。我尝试过async/await
但没有成功。
我缺少什么?
const Landing = () => {
const [api, updateApi] = useState({});
const getData = () => {
fetch('data.json')
.then((response) => response.json())
.then((data) => updateApi({api: {data}}))
}
useEffect(() => {
getData();
}, []);
console.log(api)
return (
<p>Hey!</p>
)
}
I have a simple functional component, which includes a fetch to a JSON file stored locally.
I am trying to bring in the data from the JSON file, and whilst this should be a simple task, I have come across a problem.
My console log is showing two separate logs - one is an empty object, presumably from the useState
definition and the second has the data from the fetch inside it.
Therefore, When I try to do anything with the data I'm fetching, undefined
is being returned, So I can't use it. I feel like I'm missing something obvious, but I'm not entirely sure what is going on here. I have tried async/await
without success.
What am I missing ?
const Landing = () => {
const [api, updateApi] = useState({});
const getData = () => {
fetch('data.json')
.then((response) => response.json())
.then((data) => updateApi({api: {data}}))
}
useEffect(() => {
getData();
}, []);
console.log(api)
return (
<p>Hey!</p>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要做的就是将 return 包装在 if/else 块中,并返回(例如旋转圆圈)加载指示器。当它使用来自 api 的数据重新渲染时,它会返回所需的数据表示形式。
All you need to do is to wrap the return within an if/else block, and return (for example a spinning circle) loading indicator. When it re-renders with the data from the api, it returns the desired representation of the data.
使用 async/await 语法,您可以将
fetch
请求放入useEffect
挂钩中,并设置与当前操作类似的状态。如果您使用
useState({})
初始化状态,则该值将不会未定义
。但是,如果您想在执行某些操作之前检查这一点,那么另一个答案中建议的 if/else 语句是合适的,或者如果它位于组件return
内,那么常见的模式是return
div>{api && JSON.stringify(api)};
.Using async/await syntax you can put your
fetch
requests within theuseEffect
hook and set your state similar to how you are currently doing.If you initialise the state with
useState({})
then the value won't beundefined
. If however you want to check for that before doing something then an if/else statement as suggested in another answer is suitable or if it is within the componentreturn
then a common pattern isreturn <div>{api && JSON.stringify(api)}</div>;
.