【问题标题】:How to wait while receiving a value from Useselector?从 Useselector 接收值时如何等待?
【发布时间】:2021-10-30 23:37:53
【问题描述】:

我正在实现一个简单的 MyPage。当 Mypage.tsx 首次渲染时,Redux 将用户信息保存为 useEffect。但是,当我尝试从右下方使用 UseSelector 获取数据时,它说找不到该值。

也许是因为数据在接收到值的同时立即进行处理。有没有办法解决这个问题?

错误:TypeError:无法读取 null 的属性“myPostList”

部分错误:const MyPost = userData.myPostList.map(.....

import { GetUserInfo } from "../modules/action-creator";
import { RootState } from "../modules/Store";
import "../styles/mypage.scss";



function Mypage() {
  const dispatch = useDispatch();

  useEffect(() => {
    
    dispatch(GetUserInfo())
  }, [])
  

  const userData = useSelector((state : RootState) => state.User.userData)
  

  const MyPost = userData.myPostList.map(
    (item:any, index:number) => {
      return(
        <tbody id = {"body" + index} key = {item.id}>
          <tr>
            <td id = "title">{item.postName}</td>
          </tr>
          <tr>
            <td id = "content">{item.content}</td>
          </tr>
        </tbody>
      )
    }
  )
    
  return (
        <div className="mypost">
          <div className="post_info">
            전체글 0개
            <button>글쓰기</button>
          </div>
          <table className="post_detail">{MyPost == null ? "표시할 정보가 없습니다." : MyPost}</table>
        </div>
  )
}

如下所述,数据似乎在接收到所有值之前就已处理完毕。有办法解决吗?

【问题讨论】:

    标签: reactjs typescript react-redux react-hooks dispatch


    【解决方案1】:

    您应该在使用之前检查userData 以确保它具有价值。在这种情况下你应该使用optional chaining

    const MyPost = userData?.myPostList?.map(...)
    

    【讨论】:

      【解决方案2】:

      如果上述答案对您没有帮助,那么调试您如何将这些值存储在 reducer 中可能会很有用。我还建议调试操作(在 saga/thunk 上)。

      如果您使用的是中间件,这可能是由于错误的道具名称选择,甚至是错误的请求而发生的。

      【讨论】:

      • 你能告诉我更多细节吗?
      猜你喜欢
      • 2020-02-08
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      相关资源
      最近更新 更多