![](/img/trans.png)
[英]cannot update initalState in redux-toolkit with createAsyncThunk
[英]createAsyncThunk and writing reducer login with redux-toolkit
我正在閱讀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
中寫什么? 標准減速器邏輯?
我有這個CodeSandbox ,我實現了舊的 redux 方式。 現在,需要在其中實現redux-toolkit
。
createSlice
的reducers
屬性允許您創建一個動作創建者 function 並一步響應這些動作。 您使用extraReducers
來響應已經在其他地方創建的操作,例如在異步 thunk 中。 extraReducer
只是響應一個動作,但不創建動作創建者 function。
這個例子是說除了extraReducers
之外,你還可以有一些常規的reducers
。 但是我查看了您的 CodeSandbox,在您的情況下,您不需要任何其他reducers
,因為您響應的唯一操作是來自異步 thunk 的三個操作。
由於您的createSlice
不會創建任何動作創建者,因此您實際上不需要使用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;
}
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.