我正在尝试从状态中提取数据。我正在使用redux。const {currentPost } = useSelector(state => state.posts)
我希望得到一个具有属性的对象。相反,我得到了几个未定义的,然后我得到了一个对象。
这些在开始时未定义的原因导致我无法像 const {currentPost: {id} } = useSelector(state => state.posts)
那样进一步解构并返回无法读取未定义属性的错误。
这些帖子是通过 API 获得的。
我试图通过使用检查此 currentPost
的函数来解决它。未定义,然后将 null 传递给这些属性。但是它不适合项目,而且这种解决方案容易出错。
最佳答案
随着我获得更多经验,我想为 future 的年轻前端开发人员分享我的知识
我正在使用 redux-toolkit
https://redux-toolkit.js.org/
这些未定义的值来自异步操作,因此它们的行为有时在 promise 完成之前返回未定义的值。
为了克服它并编写稳定的代码,需要添加默认值。在 redux-toolkit 你可以使用
const slice = createSlice({
name: 'posts',
initialState: {
currentPosts: {
value: {
name: ''
}
},
posts: []
},
reducers: {
...reducers
},
})
在这种情况下,您将获得 Object currentPosts,它不是未定义的。
关于javascript - React useSelector 先返回 undefined,再返回 object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59039213/