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

问题描述 投票:0回答:1

我正在阅读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))

我必须在reducersextraReducers中写些什么?标准减速器逻辑?

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

reactjs redux react-redux redux-thunk redux-toolkit
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.