Rumah > Soal Jawab > teks badan
Saya mahu melaksanakan logik membenarkan pengguna apabila halaman dimuatkan. Pada mulanya, saya ingin menyemak sama ada terdapat token dalam kuki (checkUserToken
),如果有或没有 - 调用另一个函数(fetchUserData
),该函数将来会向服务器发出请求。最后,当服务器响应时 - 调用第三个函数(setUserData
),该函数将使用用户数据填充userData
'use client' import { createSlice } from "@reduxjs/toolkit"; import { getCookie } from '@/app/untils/Cookies'; const initialState = { userData: null } export const userSlice = createSlice({ name: "userData", initialState, reducers: { checkUserToken: () => { console.log('chekc') const token = getCookie('user-token'); console.log(token) if (token) return fetchUserData(token) else return fetchUserData(false) }, fetchUserData: async (state, action) => dispatch => { return console.log('FETCH') // console.log(state) // console.log(action) }, setUserData: (state, action) => { console.log('SET USER') console.log(action) console.log(state) } } }) export const { checkUserToken, fetchUserData, setUserData } = userSlice.actions export default userSlice.reducer
Bagaimana saya boleh melaksanakan fungsi yang serupa dalam kepingan saya?
P粉4594409912023-09-18 00:41:32
Fungsi pengurangan adalah fungsi tulen, ia tidak melakukan kesan sampingan seperti tindakan penghantaran. checkUserToken
不能分发任何动作,fetchUserData
不能返回函数值。在我看来,checkUserToken
和 fetchUserData
Sebenarnya tindakan tak segerak. Buat tindakan thunk untuk mereka.
Contoh:
import { createSlice, createAsyncAction } from "@reduxjs/toolkit"; import { getCookie } from '@/app/untils/Cookies'; export const checkUserToken = createAsyncAction( "userData/checkUserToken", (_, thunkAPI) => { console.log('check'); const token = getCookie('user-token'); console.log(token); return thunkAPI.dispatch(fetchUserData(token ?? false)); }, ); export const fetchUserData = createAsyncAction( "userData/fetchUserData", async (token, thunkAPI) => { try { console.log('FETCH'); ... 异步获取逻辑 ... return /* 一些数据??? */ } catch(error) { return thunkAPI.rejectWithValue(error)); } }, ); const initialState = { userData: null, }; export const userSlice = createSlice({ name: "userData", initialState, reducers: { setUserData: (state, action) => { console.log('SET USER'); .... } }, extraReducers: builder => { builder .addCase(fetchUserData.fulfilled, (state, action) => { // 使用返回的 action.payload 值更新用户数据 }) .addCase(fetchUserData.rejected, (state, action) => { // 如有必要,设置任何错误状态 }); }, }) export const { setUserData } = userSlice.actions; export default userSlice.reducer;
Sila ambil perhatian bahawa fetchUserData
动作可以直接访问 cookies/token,fetchUserData.fulfilled
reducer case 也可以设置/更新用户数据状态。这意味着 setUserData
和 checkUserToken
tindakan mungkin tidak perlu.