React更新state后如何获取最新值?获取更新后的playerNames执行dispatch的方案
问题原因
React 中 useState 的更新方法是异步批量执行的,调用 setPlayersName 后不会立即修改当前作用域下的 playerNames 变量,当前渲染周期内拿到的始终是本次渲染闭包缓存的旧值,所以 dispatch 时拿到的就是未更新的数据。
解决方案
方案1:直接使用构造的新值触发 dispatch
你在更新 state 时已经可以构造出最新的 playerNames 数组,可以直接把这个值同时传给 state 更新和 dispatch,不需要等待 state 落地,这是最高效的方案:
const [playerNames, setPlayersName] = React.useState([]) const onClick = (event) => { const newPlayerNames = [...playerNames, event.target.value] setPlayersName(newPlayerNames) dispatch(selectPlayers(newPlayerNames)) }
方案2:用 useEffect 监听 state 变化触发 dispatch
如果你的更新 state 的逻辑分散在多个位置,不想每次手动调用 dispatch,可以用 useEffect 监听 playerNames 的变化,state 更新完成后自动触发 dispatch:
const [playerNames, setPlayersName] = React.useState([]) React.useEffect(() => { dispatch(selectPlayers(playerNames)) }, [playerNames, dispatch]) const onClick = (event) => { setPlayersName(prev => [...prev, event.target.value]) }
额外注意
原代码存在两处语法问题,可以同步修正:
- 点击回调函数名
onCLick的拼写错误,标准命名为onClick - 函数定义的语法格式错误,普通函数需要写对大括号位置,也可以改为更简洁的箭头函数写法
内容的提问来源于stack exchange,提问作者ASIF KAIF
相关产品推荐
相关产品推荐

