我正在开发Redux-ToolKit来构建一个应用程序,该应用程序使用从API获取数据。在我的Redux商店中,我有多个切片,我想访问bookingSlice中searchSlice的搜索状态。有什么方法可以解决这个问题吗?我还没能找到解决办法。
我正在寻找最佳实践
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
destination: "",
checkIn: new Date(),
checkOut: new Date(),
count: {
adults: 2,
children: 0,
rooms: 1,
},
price: {
min: 0,
max: 500000,
},
};
const searchSlice = createSlice({
name: "search",
initialState,
reducers: {
setDateRange: (state, { payload }) => {
const { startDate, endDate } = payload;
state.checkIn = startDate;
state.checkOut = endDate;
},
increment: (state, { payload }) => {
state.count[payload] += 1;
}
}
export default searchSlice.reducer;
预订切片
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const initialState = {
search: ?
bookings: [],
isLoading: false,
isSuccess: false,
isError: false,
message: "",
};
export const createBooking = createAsyncThunk(
"booking/create",
async (state, { rejectWithValue }) => {
try {
const { data } = await axios.post("api/bookings", { state });
return data;
} catch (error) {
if (error.response && error.response.data.message) {
return rejectWithValue(error.response.data.message);
} else {
return rejectWithValue(error.message);
}
}
}
);
const bookingSlice = createSlice({
name: "booking",
initialState,
reducers: {},
}
您无法访问减速器内另一个减速器的状态。但是您可以在createBooking
操作中使用getState((来获取应用程序的当前状态树。然后过滤searchSlice
中需要的信息,并将其与api响应一起从操作中返回。