如何解决React 和 MobX:typeError:无法读取未定义的属性“描述”
我在我的项目中使用了 React 17
、MobX
和 Typescript
。
在 postDetails.tsx 文件中,我想显示文章,但出现此错误:
当数据可用时,状态无法更新!
(我刚刚发现我没有收到更新的状态。这意味着我收到了状态的最后一个值。)
我该如何解决问题?
如果我注释这行代码,{/* <h1>{(postStore.postDetails.Description)}</h1> */}
,您可以看到执行行代码的顺序。与行码顺序不符!
import React,{ useEffect } from "react";
import { useParams } from "react-router-dom";
import { observer } from "mobx-react-lite";
import { useStore } from "../../app/stores/store";
import "./postDetails.css";
import { runInAction,toJS } from "mobx";
export default observer(function PostDetails() {
const { postStore } = useStore();
let { id } = useParams<{ id?: string }>();
console.log("0001 - before useEffect");
useEffect(() => {
console.log("0002 - in useEffect");
try {
runInAction(async () => {
await postStore.details(id);
})
console.log("0003 - after executing postStore.details(id)");
console.log("postStore.selectedPost : ",toJS(postStore.selectedPost));
}
catch (error) { }
},[id,postStore]);
console.log("0004 - right after the useEffect");
console.log("just befor return: ",postStore.postDetails);
return (
<>
{console.log("0005 - I expected first run useEffect for getting the data.")}
/* The data is not available */
{<h1>{(postStore.postDetails.Description)}</h1>}
</>
)
})
postStore.ts:
selectedPost: IPostModel | undefined = undefined;
details = async (id: string) => {
this.loadingInitial = true;
try {
const detailPost = await agent.Post.details(id);
runInAction(() => {
this.selectedPost = detailPost;
})
}
catch (error) {
console.log(error);
this.setLoadingInitial(false);
}
}
解决方法
除了我的评论:你的代码应该是这样的:
export default observer(function PostDetails() {
const { postStore } = useStore();
let { id } = useParams<{ id?: string }>();
useEffect(() => {
postStore.details(id)
},[id,postStore]);
if (!postStore.postDetails) {
return <div>Loading...</div>
}
return (
<h1>{(postStore.postDetails.Description)}</h1>
)
})
在没有详细信息的情况下处理。
或者您可以向您的商店添加 isLoading
标志,以使其更加透明。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。