Redux Toolkit中Pastime reducer始终返回初始值问题求助
问题排查与解决
1. Action名称不匹配且拼写错误
你的Reducer中定义并导出的action是addSeccond(注意拼写错误:正确应为Second),但组件里调用的是removeSeccond——这是一个不存在的action,dispatch它不会触发任何状态更新。另外addSeccond的逻辑是state.value -=1,名称和逻辑完全不符,建议修正名称和拼写:
// Reducer中修正action定义 reducers: { setDefault: state => { state.value = 12 }, decrementSecond: state => { // 修正名称与拼写 state.value -= 1 } } // 导出修正后的action export const { decrementSecond, setDefault } = passTimerSlice.actions
组件中改为调用正确的action:
dispatch(slices.passTimer.decrementSecond())
2. 未正确从Redux Store获取实时状态
组件中的passTimer变量没有通过useSelector绑定到Redux Store的最新状态,导致始终拿到初始值。需要添加状态获取逻辑:
import { useSelector, useDispatch } from 'react-redux' // 在组件内部获取Store中的最新状态 const passTimer = useSelector(state => state.passTimer.value) const dispatch = useDispatch()
3. 定时器ID未用useRef存储
直接声明的passTimerId会在组件每次渲染时重新创建,导致组件卸载时无法正确清除定时器。改用useRef存储:
import { useRef } from 'react' const passTimerId = useRef<NodeJS.Timeout | null>(null) useEffect(() => { dispatch(slices.passTimer.setDefault()) passTimerId.current = setInterval(() => { // ... 定时器逻辑 }, 1000) return () => { if (passTimerId.current) { clearInterval(passTimerId.current) } } }, [dispatch])
4. 闭包导致的状态捕获问题
即使你用useSelector获取了passTimer,setInterval的回调会捕获组件首次渲染时的passTimer值,后续状态更新后回调里还是旧值。解决方法是在回调内部直接从Store获取最新状态:
import { useStore } from 'react-redux' const store = useStore() // 在定时器回调中实时获取最新状态 const currentPassTimer = store.getState().passTimer.value console.log('passTimer', currentPassTimer) if (currentPassTimer <= 0) { clearInterval(passTimerId.current!) return }
5. useEffect依赖数组错误
原代码中的passState是未定义的变量,应替换为实际需要监听的依赖。如果使用store.getState()实时获取状态,依赖数组只需保留dispatch(Redux中dispatch是稳定引用)。
内容的提问来源于stack exchange,提问作者Даниил Владимиров
相关产品推荐
相关产品推荐

