React and MobX: typeError: Cannot read property 'Description' of undefined

React and MobX: typeError: Cannot read property 'Description' of undefined

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

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

TypeError: Cannot read property 'Description' of undefined.

虽然数据可用,但无法更新状态!

(我刚发现我没有收到更新的状态,意思是我收到状态的最后一个值。)

我该如何解决这个问题?

如果我注释掉这行代码,{/* <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 标记添加到您的商店,以使其更加透明。