[英]React useSelector first returns undefined, then returns object
我正在嘗試從狀態中提取數據。 我正在使用 redux。
const {currentPost } = useSelector(state => state.posts)
我希望得到一個具有屬性的對象。 相反,我得到了幾個 undefined 然后我得到了一個對象。 這些未定義的開始導致我無法像const {currentPost: {id} } = useSelector(state => state.posts)
那樣進一步const {currentPost: {id} } = useSelector(state => state.posts)
並返回無法讀取未定義屬性的錯誤。 這些帖子是通過 API 獲取的。
我試圖通過使用一個函數來解決它,該函數檢查此currentPost
是否未定義,然后將 null 傳遞給這些屬性。 但是它不適合項目並且這個解決方案容易出錯。
隨着我獲得更多經驗,我想與未來的年輕前端開發人員分享我的知識
我正在使用redux-toolkit
https://redux-toolkit.js.org/這些未定義的值來自異步操作,因此它們的行為有時在 promise 完成之前返回未定義的值。
為了克服它並編寫穩定的代碼,需要添加默認值。 在 redux-toolkit 中,您可以使用
const slice = createSlice({
name: 'posts',
initialState: {
currentPosts: {
value: {
name: ''
}
},
posts: []
},
reducers: {
...reducers
},
})
在這種情況下,您將獲得對象 currentPosts,它不是未定義的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.