如何在Redux中获取历史状态并在点击按钮时回退到之前的状态
Redux状态回退到上一版本实现方案
现有代码的reducer仅存储了key的当前值,未保留历史修改记录,无法直接实现回退逻辑,需要按以下步骤调整:
1. 修改Reducer结构,新增历史状态存储
如果仅需要回退到最近一次的修改前状态,可以直接增加previous字段存储上一次的值:
// reducer文件修改后代码 export var key = (state = { current: 0, previous: 0 }, action) => { // 注意:原代码的playload为拼写错误,标准写法为payload,建议同步修正 if (action.type === 'changeKey') { return { previous: state.current, current: action.payload } } else if (action.type === 'revertKey') { // 回退逻辑:将上一次的值赋值给当前值 return { previous: 0, current: state.previous } } else { return state } }
提示:修改后原业务代码中获取key值的逻辑需要从
state.key调整为state.key.current
如果需要支持多次连续回退,可以用数组存储全量历史记录:
// 支持多次回退的reducer写法 export var key = (state = { current: 0, history: [] }, action) => { if (action.type === 'changeKey') { return { history: [...state.history, state.current], current: action.payload } } else if (action.type === 'revertKey') { if(state.history.length === 0) return state return { history: state.history.slice(0, -1), current: state.history.at(-1) } } else { return state } }
2. 新增回退Action
在action文件中新增回退专用的action:
// action文件新增代码 export var revertKeyAction = () => { return { type: 'revertKey' } }
3. 业务代码绑定点击事件
在组件中引入dispatch和回退action即可:
import { useDispatch } from 'react-redux' import { revertKeyAction } from './你的action文件实际路径' // 组件内部代码 const dispatch = useDispatch() <Text onPress={()=>{ dispatch(revertKeyAction()) }}> 将redux-state设置为之前的redux-state值</Text>
内容的提问来源于stack exchange,提问作者Tuzi
相关产品推荐
相关产品推荐

