但是,我想添加第二个切片locationInfoSlice
,这应该会获取
调度addLocation()
操作时的数据,使用最新的
列表中的位置.
如果我对你的帖子/问题的理解是正确的,那么你实际上想要发送some个单一操作,并执行以下操作:
- 在
state.locations
数组中存储一个位置
- 处理一些异步操作/逻辑,以使用
state.locations
数组中的最后一个位置获取一些数据.
我怎样才能做到这一点呢?我想大概是extraReducers
或asyncThunk
,
但做得不对.
您可能需要同时使用这两种方法.单靠extraReducers
是行不通的,因为Reducer函数是纯同步函数,没有副作用,例如它们不能异步获取数据.我的建议是创建一个Thunk,它调度addLocation
操作来更新state.locations
状态,并使您需要的数据获取可以返回一个值,该值将用于更新extraReducers
的locationInfoSlice
‘S状态.
import { createAsyncThunk } from '@reduxjs/toolkit';
import { addLocation } from '../locationsPersistentSlice';
export const addLocationAsync = createAsyncThunk(
"locations/addLocationAsync",
async (location, thunkApi) => {
// dispatch to add new location
thunkApi.dispatch(addLocation(location));
try {
// asynchronous fetch logic
return data;
} catch(error) {
return thunkApi.rejectWithError(error);
}
},
);
import { createSlice } from '@reduxjs/toolkit';
const initialState = [];
const locationsPersistentSlice = createSlice({
name: "locations",
initialState,
reducers: {
addLocation(state, action) {
state.push(action.payload);
},
clearLocations() {
return initialState;
},
},
});
export const {
addLocation,
clearLocations,
} = locationsPersistentSlice.actions;
export default locationsPersistentSlice.reducer;
import { createSlice } from '@reduxjs/toolkit';
import { addLocationAsync } from './action';
const initialState = /* whatever this initial state value is */;
const locationInfoSlice = createSlice({
name: "locationInfo",
initialState,
extraReducers: builder => {
builder
.addCase(addLocationAsync.fulfilled, (state, action) => {
// update state with fetched data
})
.addCase(addLocationAsync.rejected, (state, action) => {
// update state with error status???
})
.addCase(addLocationAsync.pending, (state, action) => {
// set any pending/loading state
});
},
});
export default locationInfoSlice.reducer;
在用户界面中,它不是直接分派addLocation
操作,而是分派addLocationAsync
操作.
import { useDispatch } from 'react-redux';
import { addLocationAsync } from './action';
...
const dispatch = useDispatch();
...
dispatch(addLocationAsync(/* some location value */));
...