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

时间:2020-05-26 10:59:54

标签: reactjs redux react-redux redux-thunk 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))


我必须在reducersextraReducers中写什么?标准的reducer逻辑?

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

1 个答案:

答案 0 :(得分:0)

reducerscreateSlice 属性允许您创建一个动作创建器函数并一步响应这些动作。您可以使用 extraReducers 来响应已在其他地方创建的操作,例如异步 thunk。 extraReducer 仅响应操作,但不创建操作创建器函数。

该示例说明除了 reducers 之外,您还可以使用一些常规的 extraReducers。但是我查看了您的 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;
    }
  }
})