从createSlice中的减速器释放的正确方法



在createSlice中,从reducer中分配操作的正确方法是什么。例如,我该如何调用下面的getX((:

import axios from 'axios';
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
export const getBusiness = createAsyncThunk('business/getBusiness', () => {
return axios
.get('https://api.github.com/users/mapbox')
.then((response) => {
if (!response.status == 200) throw Error(response.statusText);
return response.data;
})
.then((data) => data);
});
export const getX = createAsyncThunk('business/getX', () => {
return axios
.get('https://my-json-server.typicode.com/typicode/demo/posts')
.then((response) => {
if (!response.status == 200) throw Error(response.statusText);
return response.data;
})
.then((data) => data);
});
export default createSlice({
name: 'business',
initialState: {
loading: false,
error: '',
data: [],
test : []
},
reducers: {
// REGULAR REDUCERS
},
extraReducers: {
[getBusiness.pending]: (state) => {
state.loading = true;
},
[getBusiness.rejected]: (state, action) => {
state.loading = false;
state.error = action.error.message;
},
[getBusiness.fulfilled]: (state, action) => {
state.loading = false;
state.data = action.payload;
getX() //what is the correct way to dispatch another action??
},
[getX.pending]: (state) => {
state.loading = true;
},
[getX.rejected]: (state, action) => {
state.loading = false;
state.error = action.error.message;
},
[getX.fulfilled]: (state, action) => {
state.loading = false;
state.test = action.payload;
}
}
});

从reducer调度是不允许的。减速器必须没有副作用,而调度在很大程度上是一种副作用。

在这种情况下,您需要使用中间件。

要么使用目前正在测试的RTK动作侦听器中间件,要么只是将原始的thunk封装在另一个thunk中。

类似的东西

const getBusinessAndGetX = () => (dispatch) => {
try {
await dispatch(getBusiness()).unwrap()
dispatch(getX())
} catch {}
}

然后CCD_ 1

最新更新