React 18 渲染在 setState 之前导致错误
因此,我一直在尝试制作如下所示的超级简单的 api 请求,并将其存储到 useState var 中,但是在最近更新到 React 18 后,我在渲染任何内容之前收到错误,因为 str 返回为未定义。并不是从 api 返回数据失败,而是 str 返回未定义,因为它没有等待数据状态被设置。
我不知道该怎么做,因为在以前的 React 版本中,我没有遇到过这个问题。有谁知道可能是什么问题吗?我检查了文档,但似乎没有提到这是需要注意的事情。
const Component = () => {
const [data, setData] = useState(null);
const str = data.data.sentence
useEffect(() => {
fetch("https://api.hatchways.io/assessment/sentences/2")
.then((res) => res.json())
.then((data) => setData(data));
}, []);
return (
<div>
<p>{str}</p>
</div>
)
}
So I've been trying to make super simple api request like the following and store it into a useState var, however after the recent update to React 18, I get an error before anything can render because str returns as undefined. It is not a failure to return data from the api but str returning as undefined because it is not waiting for the state of data to be set.
I am not sure of what to do because in previous versions of React, I have not had this problem. Has anyone figured out what could possible be the issue? I checked the docs but there doesn't seem to be any mention of this being something to be aware of.
const Component = () => {
const [data, setData] = useState(null);
const str = data.data.sentence
useEffect(() => {
fetch("https://api.hatchways.io/assessment/sentences/2")
.then((res) => res.json())
.then((data) => setData(data));
}, []);
return (
<div>
<p>{str}</p>
</div>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为当您将其声明为
str
时,data.data.sentence
未定义,整个组件将抛出错误。所以你需要设置它,因为它可能为空。旧版本的 React 一直都是这种情况,因此您可能正在做其他事情。
我个人会在那里有一个加载状态,这样你就不会在没有值的情况下渲染
str
。Because
data.data.sentence
is undefined when you declare it asstr
the whole component will throw an error. So you need to set it as it could be null.This has always been the case with older versions of React so you were probably doing something else.
I personally would have a loading state in there so you wouldn't render
str
without there being a value.