[英]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.