如何使用 createEntityAdapter() 方法在 redux 中添加一个数组作为初始数据

How to add an array as initial data in redux with its createEntityAdapter() method

只想添加一个数组作为初始数据,这让我能够显示一些默认数据。

eventSlice.ts 

import {
  createEntityAdapter,
  createSlice,
  EntityAdapter,
} from "@reduxjs/toolkit";
import { RootState } from "../store";

export type EventType = {
  id: string;
  title: string;
  description: string;
  location: string;
  date: string;
  image: string;
  isFeatured: boolean;
};

const eventAdapter: EntityAdapter<EventType> = createEntityAdapter<EventType>({
  // sortComparer: (a: any, b: any) => b.date.localCompare(a.date),
});

const initialState = eventAdapter.getInitialState({
  status: "idle",
  error: null,
});

export const eventSlice = createSlice({
  name: "event",
  initialState,
  reducers: {
    eventLoading(state, action) {
      if (state.status === "idle") {
        state.status = "pending";
      }
    },
    eventCleaded: eventAdapter.removeAll,
    eventAdded: eventAdapter.addOne,
    eventUpdated: eventAdapter.updateOne,
  },
});

export const eventSelector = eventAdapter.getSelectors<RootState>(
  (state) => state.events
);
export const { eventAdded, eventCleaded, eventLoading, eventUpdated } =
  eventSlice.actions;

export default eventSlice.reducer;

并且想在通过其他方法访问 sliceEvent.ts 之前添加一些数据: 此外,getAllEvents() 只是包含一些数据的数组,我想将它们添加到此流程中

import { getAllEvents } from "../../../dummy-data";
import { useAppDispatch } from "../hooks";
import { eventAdded, EventType } from "./eventSlice";

export function CreateEvents() {
  const dispatch = useAppDispatch();
  const events: EventType[] = getAllEvents();
  const createEvents = events.map((event) =>
    dispatch(
      eventAdded({
        id: event.id,
        date: event.date,
        description: event.description,
        image: event.image,
        isFeatured: event.isFeatured,
        location: event.location,
        title: event.title,
      })
    )
  );
}

.......................

如果您确实如上面的代码所建议的那样同步提供了该数据,只需从头添加即可。


const initialState = eventAdapter.addMany(
  eventAdapter.getInitialState({
    status: "idle",
    error: null,
  }),
  [
    // your initial items go here
  ]
);

像上面那样在组件渲染中这样做会导致无限渲染循环。

如果您没有同步可用的数据,请使用 state: uninitialized 或类似的东西初始化您的状态,在 useEffect 中获取数据并发送它,同时显示加载屏幕或其他东西.您不能“暂停”React 渲染以等待异步操作,但您始终可以只显示加载微调器等。