React条件渲染加载组件状态更新逻辑失效问题排查
问题分析与解决方案
你的问题核心是异步操作的执行顺序错误,导致isLoading状态刚被设为true就立刻被重置为false,Loader组件根本来不及渲染。
问题代码的关键问题
axios.post是异步请求,它不会阻塞后续代码执行。你在调用axios.post后直接执行了setIsLoading(false),这行代码会在请求还没完成时就运行,覆盖掉之前的setIsLoading(true),最终isLoading始终是false,所以Loader无法显示。
修复后的代码
把setIsLoading(false)移到异步请求的回调函数中,确保只有当请求完成(成功或失败)后才关闭加载状态:
const [isLoading, setIsLoading] = useState(false); const joinRoom = () => { const roomKey = roomKeyInput.current.value; if(roomKey == null) return let req = { sessionId: sessionId, socketId: socket.id } setIsLoading(true) axios.post(`${hostName}/join-room/${roomKey}`, req) .then((res)=>{ if(res.data.success){ setIsRoomAdmin(false) setRoomKey(res.data.roomKey) setConnectedToRoom(true); socket.emit('connect-to-room', { roomKey: roomKey }) } // 请求成功后关闭加载 setIsLoading(false) }).catch(function (error) { console.log(error); // 请求失败也要关闭加载,避免一直显示Loader setIsLoading(false) }); } return ( <> {isLoading && <Loader />} </> )
补充说明
- 手动设
isLoading初始值为true能显示Loader,是因为没有后续代码立刻把它改成false,状态保持为true直到你手动修改。 - React状态更新是异步批量的,你原来代码中的两次
setIsLoading会被合并,最终只保留最后一次的false,这也是Loader不显示的原因之一。
内容的提问来源于stack exchange,提问作者Harsh Kumar
相关产品推荐
相关产品推荐

