React Native中Redux dispatch后状态未变更的问题求助
调用Redux Toolkit的dispatch后状态无变化的问题修复
我已经花了一天时间修复这个bug,但调用dispatch后状态始终没有变化。我的Slice代码和Redux Toolkit官网示例几乎一致,以下是我的代码:
App.tsx
export const StateDisplay = () => { const data = useAppSelector(selectErrors); const dispatch = useAppDispatch(); function onPressMethod() { dispatch( errorActions.addNewOne({ type: "thisIsAType", value: "thisIsAValue" }) ); } return ( <View> <Text>STATE :</Text> <Button title="add" onPress={onPressMethod}></Button> <FlatList data={data} renderItem={({ item }) => <Text>{item.value}</Text>} /> <Text></Text> </View> ); };
Store
export const store = configureStore({ reducer: { errors: errorListSlice.reducer, }, });
Slice
export interface dto { value: string; type: string; } export type RootState = ReturnType<typeof store.getState>; export type AppDispatch = typeof store.dispatch; export const selectErrors = (state: RootState) => state.errors; const initialState: dto[] = [ { value: "val1", type: "type1" }, { value: "val1", type: "type1" }, ]; export const errorListSlice = createSlice({ name: "errorList", initialState, reducers: { addNewOne: (state, action: PayloadAction<dto>) => { state = [ ...state, { value: action.payload.value, type: action.payload.type, }, ]; }, }, }); export const errorActions = errorListSlice.actions; export default errorListSlice.reducer;
问题原因
问题出在Slice的addNewOne reducer中。Redux Toolkit的createSlice基于Immer库,它允许你用"可变"写法实现不可变状态更新,但核心规则是不能直接给state参数重新赋值。你当前的代码只是把新数组赋值给了函数参数state,Immer无法追踪到这个变量赋值操作,原状态引用未被修改,所以Redux感知不到状态变化。
修复方案
有两种可行的修复方式:
方式一:利用Immer特性直接修改原数组
使用数组push方法添加新元素,Immer会自动将这个"修改"转换为不可变状态更新:
addNewOne: (state, action: PayloadAction<dto>) => { state.push({ value: action.payload.value, type: action.payload.type, }); }
方式二:显式返回新状态数组
直接返回新数组,这是Redux传统的不可变更新方式,无需依赖Immer自动转换:
addNewOne: (state, action: PayloadAction<dto>) => { return [ ...state, { value: action.payload.value, type: action.payload.type, }, ]; }
两种方式都能解决问题,任选其一即可。
内容的提问来源于stack exchange,提问作者Flap13
相关产品推荐
相关产品推荐

