使用React-Redux进行类型化调度



看完官方教程后,我真的不明白如何正确地调度react-redux@8.0.5的更新。

我的设置是这样的:

export const mySlice = createSlice({
name: 'MyItem',
initialState: { field1: 'hello, world', field2: 0 },
reducers: {
setField: (state: { field1: string; field2: number }, action: PayloadAction<string>) => {
state.field1 = action.payload;
},
},
});
export const store = configureStore({
reducer: {
myItem: mySlice.reducer,
},
});
export type AppDispatch = typeof store.dispatch;

在组件内部,我正在与分派作斗争:

const dispatch: AppDispatch = useDispatch();
// Resembles the `dispatch(increment())}` from the offical example, but I get a type error and I can't pass my update data.
// Additionally, the signature looks wrong (it looks like a reducer)
dispatch(mySlice.actions.setField());
// Since the signature doesn't match, TypeScript complains with `Void function return value is used`
dispatch(mySlice.actions.setField('newValue')) 
// TypeScript won't complain, but it doesn't seem like I could pass my update this way
dispatch(mySlice.actions.setField);
// TypeScript won't complain, but it's neither typed nor the recommended approach anyway
dispatch({ type: 'Idontexist', someValue: "hey" });

谢谢你的帮助!

编辑:解决方案似乎是使用解构模式:

export const {setField} = mySlice.actions;
...
dispatch(setField('newValue'))

但我不知道为什么这是工作,而直接访问dispatch(mySlice.actions.setField('newValue'))没有。

正确导出

export const {setField} = mySlice.actions;

现在你可以导入它并调度(setField())

相关内容

  • 没有找到相关文章

最新更新