[英]Fetching data and updating the isLoading but setState isn't updating correctly and it always ends up being the initial isLoading state
const App = () => {
const [user, setUser] = useState({
name: "",
organisationName: "",
id: "",
isLoading: false,
});
useEffect(() => {
const userId = getUserIdFromParams();
if (userId) {
setUser({...user, isLoading: true}); // dispatch(STARTED_FETCHING_LEAD)
(async () => {
const retrievedUser = await getLeadFromDatabase(leadId);
if (retrievedUser) setUser({...user, ...retrievedUser});
})();
}
setUser({...user, isLoading: false});
}, []);
我期望發生的情況如下:
如果 URL 參數中有 userId,則 isLoading 設置為 true(組件相應更新)。 然后當檢索到用戶時,state 將設置為用戶詳細信息,最后 state 最后一次更新為 isLoading false。
怎么了:
State 不會相應地更新,它總是最終與 useState 中的一組相同的 state。 因此,如果我在原始 state 中設置 isLoading: true。 加載組件將無限期顯示,當我設置為 false 時,它最終為 false。
有人知道這里發生了什么嗎? 非常感謝所有幫助:)
你不需要寫setUser({...user, isLoading: true})
你可以說setUser({ isLoading: true })
查看文檔
您異步檢索用戶,但同步重置isLoading
為 true。 因此,在加載用戶之前, isLoading
很可能是錯誤的。 我會這樣重寫它:
useEffect(() => {
const userId = getUserIdFromParams();
if (userId) {
setUser({...user, isLoading: true}); // dispatch(STARTED_FETCHING_LEAD)
(async () => {
const retrievedUser = await getLeadFromDatabase(leadId);
if (retrievedUser) setUser({...retrievedUser, isLoading: false});
})();
}
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.