如何在redux-toolkit中重用状态

kgqe7b3p  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(198)

我正在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: {},
}
bnlyeluc

bnlyeluc1#

你不能在一个reducer中访问另一个reducer的状态。但是你可以在createBooking操作中使用getState()来获取你的应用程序的当前状态树。然后从searchSlice中过滤你需要的信息,并将其与api响应一起从操作中返回。

相关问题