React useSelector 首先返回未定义,然后返回对象

Arc*_*ech 5 javascript reactjs redux react-redux

我正在尝试从状态中提取数据。我正在使用 redux。

const {currentPost } = useSelector(state => state.posts)

我希望得到一个具有属性的对象。相反,我得到了几个 undefined 然后我得到了一个对象。这些未定义的开始导致我无法进一步解构const {currentPost: {id} } = useSelector(state => state.posts)并返回无法读取未定义属性的错误。这些帖子是通过 API 获取的。

我试图通过使用一个函数来解决它,该函数检查这currentPost是否未定义,然后将 null 传递给这些属性。但是它不适合项目并且这个解决方案容易出错。

Arc*_*ech 5

随着我获得更多经验,我想与未来的年轻前端开发人员分享我的知识

我正在使用redux-toolkit https://redux-toolkit.js.org/ 这些未定义的值来自异步操作,因此它们的行为有时在承诺完成之前返回未定义的值。

为了克服它并编写稳定的代码,需要添加默认值。在 redux-toolkit 中,您可以使用

const slice = createSlice({
  name: 'posts',
  initialState: {
    currentPosts: {
      value: {
        name: ''
      }
    },
    posts: []
  },
  reducers: {
    ...reducers
    },
})

Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将获得对象 currentPosts,它不是未定义的。