我创建了一个新的react redux工具包应用程序,但在尝试从createAsyncThunk调用内部调用dispatch时遇到了问题。
export const fetchBoardAsync = createAsyncThunk(
'board/fetchBoard',
async (boardId: string, thunkApi: { dispatch: (arg0: { type: string; response: { data: any; }; "": any; }) => void; } ) => {
const response = await fetchBoard();
console.log('fetch board returned data...' + JSON.stringify(response.data.board));
//thunkApi.dispatch({ type: 'board/setBoard', payload: response.data })
return response.data;
}
);
export const boardSlice = createSlice({
name: 'board',
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: {
setBoard: (state, action: PayloadAction<any>) => {
state.board = action.payload;
}
},
// The `extraReducers` field lets the slice handle actions defined elsewhere,
// including actions generated by createAsyncThunk or in other slices.
extraReducers: (builder) => {
builder
.addCase(fetchBoardAsync.fulfilled, (state, action) => {
state.board += action.payload.data;
});
},
});
所以我现在已经把电话评论出来了:
//thunkApi.dispatch({ type: 'board/setBoard', payload: response.data })
当我取消注释时,我会得到以下类型的错误:
Argument of type '{ type: string; payload: any; }' is not assignable to parameter of type '{ type: string; response: { data: any; }; "": any; }'.
Object literal may only specify known properties, and 'payload' does not exist in type '{ type: string; response: { data: any; }; "": any; }'.ts(2345)
thunkApi参数上的类型也正确吗?
async (boardId: string, thunkApi: { dispatch: (arg0: { type: string; response: { data: any; }; "": any; }) => void; } ) => {
我需要帮助尝试调用这个调度,这样我就可以使用这个方法将有效负载响应保存到我的redux存储中。。。
createAsyncThunk
已经抽象出了在一切正常时在其内部进行调度的步骤,使用redux工具包,您所要完成的thunk就是返回一个值,所述值将在操作对象中传递给thunk.完成。这意味着您不需要向setBoard
reducer进行调度,fetchBoardAsync.fulfilled
额外的reducer将收到您的createAsyncThunk
的返回。thunkApi
用于其他需要取消请求或错误拒绝请求的情况。