React 和 MobX:typeError:无法读取未定义的属性“描述”

问题描述

我在我的项目中使用了 React 17MobXTypescript

在 postDetails.tsx 文件中,我想显示文章,但出现此错误

类型错误:无法读取未定义的属性“描述”。

当数据可用时,状态无法更新!

(我刚刚发现我没有收到更新的状态。这意味着我收到了状态的最后一个值。)

我该如何解决问题?

The error

如果我注释这行代码{/* <h1>{(postStore.postDetails.Description)}</h1> */},您可以看到执行行代码的顺序。与行码顺序不符!

content of return() has no any fetched data

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 标志,以使其更加透明。