(Redux工具包)如何访问CreatesLice之外的状态

发布于 2025-02-11 18:47:30 字数 514 浏览 1 评论 0原文

在我的项目中,我想在slice.js中放置尽可能多的逻辑和功能。有时我想创建或导出createSlice之外的功能

const checkValid = () => {
   ```need to access the current state to check for validation```
}

export const boardSlice = createSlice({
    name: 'board',
    initialState,
    reducers: {
       check: (state, actions) => {
         checkValid(actions.payload);
       }
    }
});

:解决方案是在降低器中直接将状态与action.payload一起传递。但是有更好或官方的方法吗?另外,将与逻辑放在切片中一样好吗?非常感谢。

In my project, I want to put as much as logic and function inside the the slice.js. Sometime I want to create or export the function outside of the createSlice like this:

const checkValid = () => {
   ```need to access the current state to check for validation```
}

export const boardSlice = createSlice({
    name: 'board',
    initialState,
    reducers: {
       check: (state, actions) => {
         checkValid(actions.payload);
       }
    }
});

The checkValid need to access the state in the store, my current solution is directly passing the state as props along with the actions.payload in the reducer. But is there a better or official way of doing this? Also, is it good to put as much as logic inside the slice? Much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

为你拒绝所有暧昧 2025-02-18 18:47:30

让我与您分享使用的方法,希望它有助于

mport { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import authService from "Services/authService";
import { logOutUser } from "Services/userServices";

const user = JSON.parse(localStorage.getItem("user"));

const initialState = {
  user: user ? user : null,
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

// Register user
export const register = createAsyncThunk("user/register", async (user, thunkAPI) => {
  try {
    return await authService.register(user);
  } catch (error) {
    const message =
      (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
    return thunkAPI.rejectWithValue(message);
  }
});

// Login user
export const login = createAsyncThunk("user/login", async (user, thunkAPI) => {
  try {
    const { username, password } = user;
    const res = await authService.loginUser(username, password);
    return res;
  } catch (error) {
    const message =
      (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
    return thunkAPI.rejectWithValue(message);
  }
});

export const logout = createAsyncThunk("user/logout", async () => {
  try {
    return await logOutUser();
    return res;
  } catch (error) {
    const message =
      (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
    return thunkAPI.rejectWithValue(message);
  }
});

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = "";
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(register.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(register.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.user = action.payload;
      })
      .addCase(register.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
        state.user = null;
      })
      .addCase(login.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.user = action.payload;
      })
      .addCase(login.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
        state.user = null;
      })
      .addCase(logout.fulfilled, (state) => {
        state.isSuccess = true;
        localStorage.removeItem("token");
        localStorage.removeItem("user");
        state.user = null;
      });
  },
});

export const { reset } = userSlice.actions;
export default userSlice.reducer;

更​​多地使用额外的还原器
结帐此 https://www.youtube.com/watch?v

Let me share with you what am using, hope it helps

mport { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import authService from "Services/authService";
import { logOutUser } from "Services/userServices";

const user = JSON.parse(localStorage.getItem("user"));

const initialState = {
  user: user ? user : null,
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

// Register user
export const register = createAsyncThunk("user/register", async (user, thunkAPI) => {
  try {
    return await authService.register(user);
  } catch (error) {
    const message =
      (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
    return thunkAPI.rejectWithValue(message);
  }
});

// Login user
export const login = createAsyncThunk("user/login", async (user, thunkAPI) => {
  try {
    const { username, password } = user;
    const res = await authService.loginUser(username, password);
    return res;
  } catch (error) {
    const message =
      (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
    return thunkAPI.rejectWithValue(message);
  }
});

export const logout = createAsyncThunk("user/logout", async () => {
  try {
    return await logOutUser();
    return res;
  } catch (error) {
    const message =
      (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
    return thunkAPI.rejectWithValue(message);
  }
});

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = "";
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(register.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(register.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.user = action.payload;
      })
      .addCase(register.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
        state.user = null;
      })
      .addCase(login.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.user = action.payload;
      })
      .addCase(login.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
        state.user = null;
      })
      .addCase(logout.fulfilled, (state) => {
        state.isSuccess = true;
        localStorage.removeItem("token");
        localStorage.removeItem("user");
        state.user = null;
      });
  },
});

export const { reset } = userSlice.actions;
export default userSlice.reducer;

for more clalification on the use of extra reducers
checkout this https://www.youtube.com/watch?v=mvfsC66xqj0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文