为什么Redux dispatch action会覆盖store值,如何解决多次dispatch数据丢失问题
问题根本原因
你当前的Redux reducer逻辑存在错误,每次触发action返回新状态时,没有保留原state中的其余字段,直接返回了仅包含当前修改字段的对象,所以无论dispatch多少次,前一次修改的其他字段都会被覆盖丢失,和dispatch的触发时机没有关系。
解决方案1:修改reducer逻辑保留原有状态(推荐)
把reducer中返回新状态的逻辑调整为:先解构旧state的全部字段,再覆盖需要更新的字段,修正后的reducer代码如下:
const counterReducer = ( state = initialState, action ) => { if (action.type === "access_token") { // 先展开原有state的所有字段,再覆盖要修改的字段 return { ...state, access_token: action.payload, }; } if (action.type === "firebase_userId") { return { ...state, firebase_userId: action.payload, }; } return state; };
修改完成后你原本的两次dispatch逻辑不需要调整,两次的payload都会正常保存在store里,不会互相覆盖。
额外提示:你当前store代码中引入的React和symbolicateStackTrace没有被使用,可以直接删除,不影响功能运行
解决方案2:合并为一次dispatch(可选)
如果想减少dispatch触发次数,也可以自定义合并类型的action,一次性传入两个参数:
对应dispatch写法
dispatch({ type: "SET_USER_CREDENTIAL", payload: { access_token: googleUser.accessToken, firebase_userId: result.user.uid } });
对应reducer新增逻辑
const counterReducer = ( state = initialState, action ) => { if (action.type === "SET_USER_CREDENTIAL") { return { ...state, ...action.payload }; } // 其余原有逻辑保留即可 if (action.type === "access_token") { return { ...state, access_token: action.payload, }; } if (action.type === "firebase_userId") { return { ...state, firebase_userId: action.payload, }; } return state; };
内容的提问来源于stack exchange,提问作者Matt Laszcz
相关产品推荐
相关产品推荐

