react hook的setState怎么保证更新呢

RT,有一个商品列表,我需要在列表上改写商品订单的状态,所以我用一个state保存当前操作的state的ID,但是因为state是异步更新我使用setState后state会出现旧值。我到setTimeout里面在下一轮循环使用这个state依然不会更新?

setCurrentId(id) // 设置当前ID

// 紧接着异步操作
setTimeout(() => {
    post({
        currentId
    }).then(() => {
     // ...
    })
})
阅读 5.1k
2 个回答

当状态发生改变,你可以使用useEffect来触发更新

// 后面参数currentId是可选的,如果有,则在currentId变化时触发
useEffect(() => {
    setCurrentId(id)
}, [currentId])

按题主需求,是想要在改变state后立马使用新的state去请求数据,给出方案如下:

  1. 使用 useRef 记录最新的状态值

    const resultState = useRef(null)
    
    setCurrentId(id) // 设置当前ID
    resultState.current = id 
  2. 请求时使用 useRef 中记录的最新状态值

    post({
        currentId:resultState.current
    }).then(() => {
     // ...
    })

按上述方法可以解决你的问题,还有另一种写法。


在下次render时再发异步请求,但注意要使用竞态机制:

const currentReq = useRef(0) // 竞态机制

setCurrentId(id) // 设置当前ID

useEffect(() => {
    const current = currentReq.current
    post({
        currentId
    }).then(() => {
     if(current === currentReq.current ){
        // ...
     }
     
    })
    return ()=>currentReq.current++
}, [currentId])
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题