简体   繁体   English

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

[英]React useSelector first returns undefined, then returns object

I'm trying to extract data from state.我正在尝试从状态中提取数据。 I'm using redux.我正在使用 redux。

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

I expected to get an object with properties.我希望得到一个具有属性的对象。 Instead I get couple of undefined and then I get an object.相反,我得到了几个 undefined 然后我得到了一个对象。 These undefined on the start causes that I can't destructure further like const {currentPost: {id} } = useSelector(state => state.posts) and returns error that it can't read property of undefined.这些未定义的开始导致我无法像const {currentPost: {id} } = useSelector(state => state.posts)那样进一步const {currentPost: {id} } = useSelector(state => state.posts)并返回无法读取未定义属性的错误。 These posts are obtained by API.这些帖子是通过 API 获取的。

I've tried to workaround it by use a function which checks if this currentPost is undefined and then pass null into these properties.我试图通过使用一个函数来解决它,该函数检查此currentPost是否未定义,然后将 null 传递给这些属性。 However it's not suitable for project and this solution is error prone.但是它不适合项目并且这个解决方案容易出错。

As I get more experience I want to share my knowledge for future young frontend developers随着我获得更多经验,我想与未来的年轻前端开发人员分享我的知识

I'm using redux-toolkit https://redux-toolkit.js.org/ These undefined values are from async operations, so its their behaviour that sometimes before promise is completed return undefined value.我正在使用redux-toolkit https://redux-toolkit.js.org/这些未定义的值来自异步操作,因此它们的行为有时在 promise 完成之前返回未定义的值。

To overcome it and write stable code there is a need to add default values.为了克服它并编写稳定的代码,需要添加默认值。 In redux-toolkit you can use在 redux-toolkit 中,您可以使用

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

In that case you'll get Object currentPosts, which is not undefined.在这种情况下,您将获得对象 currentPosts,它不是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM