如何使用 Redux Toolkit 设置两个独立的状态?

How to set two separate States with Redux Toolkit?

我正在尝试使用 Redux Toolkit 建立两个独立的状态,一个称为 posts,另一个称为 countTest。但是,目前这两个状态共享相同的值。

posts设置为显示[]的值,countTest设置为显示0的值。如何区分这两种状态以显示其唯一值?

我的动作文件

import { createSlice } from "@reduxjs/toolkit";
import { database, auth } from "../firebase";
import { ref, set } from "firebase/database";

export const counterSlice = createSlice({
  name: "posts",
  initialState: {
    value: [],
  },
  reducers: {
    createAccount: (state, action) => {
      const user = auth.currentUser;
      const uid = user.uid;

      set(ref(database, `users/${uid}`), {
        email: action.payload.email,
        name: action.payload.name,
      });
    },
  },
});

export const testSlice = createSlice({
  name: "countTest",
  initialState: { value: 0 },
  reducers: {
    incrementAmount: (state, action) => {
      state.value = state.value + 1;
    },
    decrementAmount: (state, action) => {
      state.value = state.value - 1;
    },
  },
});

export const { createAccount, countTest } = counterSlice.actions;

export default counterSlice.reducer;

我的商店文件

import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./actions";

export const store = configureStore({
  reducer: {
    posts: counterReducer,
    countTest: counterReducer,
  },
});

我知道在我的商店文件中我使用的是 counterReducer,但没有具体提及操作 createAccountcountTest。我如何去检索每一个的唯一值并在商店中展示?我是否需要为每个操作创建一个单独的文件(这是最佳做法吗?)而不是将所有操作都放在一个文件中?

感谢您的帮助

您需要使用 createAction(在另一个文件上或在其中的一个切片导入操作上)并使用 extraReducer。

文档: https://redux-toolkit.js.org/api/createSlice(最后一个例子)

示例创建操作:

export const incrementAll = createAction("incrementAll");

在你的切片上使用:

reducers : {//what you have for other things},
extraReducers: (builder) => {
    builder.addCase(incrementAll, (state) => {
      state.value++;
    });

如果您需要更多解释,请参阅文档以获取更多信息或在此处发表评论