gpt4 book ai didi

reactjs - createAsyncThunk 并使用 redux-toolkit 编写 reducer 登录

转载 作者:行者123 更新时间:2023-12-04 13:56:12 24 4
gpt4 key购买 nike

我在看 createAsyncThunk文档,感觉有点与流程混淆。这是来自文档:

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'

// First, create the thunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)

// Then, handle actions in your reducers:
const usersSlice = createSlice({
name: 'users',
initialState: { entities: [], loading: 'idle' },
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[fetchUserById.fulfilled]: (state, action) => {
// Add user to the state array
state.entities.push(action.payload)
}
}
})

// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))

我必须在 reducers 中写什么和 extraReducers ?标准 reducer 逻辑?

我有这个 CodeSandbox我实现了旧的 redux 方式。现在,需要实现 redux-toolkit在里面。

最佳答案

reducers createSlice 的属性(property)允许您制作 Action 创建器功能并一步响应这些 Action 。您使用 extraReducers响应已在其他地方创建的操作,例如异步 thunk。 extraReducer仅响应 Action 但不创建 Action 创建器功能。
这个例子是说你可以有一些常规的 reducers除了extraReducers .但是我查看了您的 CodeSandbox,在您的情况下,您不需要任何其他 reducers因为您响应的唯一操作是来自 async thunk 的三个操作。
由于您的 createSlice不会制作您不需要使用的任何 Action 创建器 createSlice .你可以使用它,但你也可以只使用 createReducer .

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'

export const fetchUserFromGithub = createAsyncThunk(
'users/fetch',
async (username) => {
const response = await axios.get(
`https://api.github.com/users/${username}`
);
return response.data
}
)

const usersSlice = createSlice({
name: 'users',
initialState: {
user: null,
fetchingUser: false,
fetchingError: null
},
reducers: {},
extraReducers: {
[fetchUserFromGithub.pending]: (state, action) => {
state.fetchingUser = true;
state.fetchingError = null;
},
[fetchUserFromGithub.rejected]: (state, action) => {
state.fetchingUser = false;
state.fetchingError = action.error;
}
[fetchUserFromGithub.fulfilled]: (state, action) => {
state.fetchingUser = false;
state.user = action.payload;
}
}
})

关于reactjs - createAsyncThunk 并使用 redux-toolkit 编写 reducer 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62020623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com