React using REDUX useSelector error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'projectname')

React using REDUX useSelector error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'projectname')

我在使用 useSelector 加载数据时收到此错误,但它 returns 是正确的信息。我发现数据是在错误后加载的,但是如何避免呢?:

           const dispatch = useDispatch();
            const { identify } = useParams();

            //set loader
            const [loaderthis, setLoaderthis] = useState(true);
            const [breadCrumb, setBreadCrumb] = useState("");

            //send identify to REDUX to obtain this ID project
            useEffect(() => {
                if (identify) {
                const fetchData = () => {
                    return dispatch(getProjectById(identify));
                };
                fetchData();
                }
            }, []);

            //get this project from REDUX
            const getProj = useSelector(
                (state: RootState) => state.projectreducer.detail
            );
            //HERE WHEN I LOG getProj i get the data objet right!!!
            console.log(getProj)

            //set loading to false when proyecto is valid
            useEffect(() => {
                setTimeout(() => {
                const fetchBread = async () => {
                    let namePro = getProj.projectname;  //ERROR HERE??
                    return setBreadCrumb(namePro || "");
                };
                fetchBread();
                setLoaderthis(false);
                }, 500);
            }, [loaderthis]);

编辑:这是对象returns

我猜 getProj 状态切片是在 API 调用后填充的。所以在 API 调用响应之前它是未定义的,尝试使用可选链 getProj?.projectname;并且,将 getProj 添加为 useEffect 钩子的依赖项,以便当 getProj 更改时, useEffect 将再次执行。