如何在没有 createSlice 的情况下使用 createThunkAsync

How to use createThunkAsync without createSlice

我有一个简单的减速器。我在 combineReducers 中使用,然后在 createStore 中使用。我想使用 async thunks 来使用 axios 获取数据。我在任何地方都看不到的是如何在没有 createSlice 函数的情况下使用 thunk。你能指点我或解释一下吗?

import { createAction } from '@reduxjs/toolkit'

export const setMyData = createAction('myData/setMyData')

export const initialState = {
    myData: []
};

const myDataReducer = (state = initialState, action) => {
    switch (action.type) {
        case setMyData.type:
            return {
                ...state,
                myData: action.payload
            };
        default:
            return { ...state };
    }
};

export default myDataReducer;

createAsyncThunk 函数的第一个参数是 type 将生成动作类型。您可以在 reducer 函数中使用这些操作类型。

例如,'data/getPostById' 类型参数将生成这些操作类型:

  • pending: 'data/getPostById/pending'
  • fulfilled: 'data/getPostById/fulfilled'
  • rejected: 'data/getPostById/rejected'

例如

import { combineReducers, configureStore, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

const getPostById = createAsyncThunk('data/getPostById', () => {
  return axios.get(`https://jsonplaceholder.typicode.com/posts/1`).then((res) => res.data);
});

const postReducer = (state = {}, action) => {
  switch (action.type) {
    case 'data/getPostById/fulfilled':
      return action.payload;
    default:
      return state;
  }
};

const rootReducer = combineReducers({
  post: postReducer,
});

const store = configureStore({ reducer: rootReducer });
store.subscribe(() => {
  console.log(store.getState());
});
store.dispatch(getPostById());

输出:

{ post: {} }
{
  post: {
    userId: 1,
    id: 1,
    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    body: 'quia et suscipit\n' +
      'suscipit recusandae consequuntur expedita et cum\n' +
      'reprehenderit molestiae ut ut quas totam\n' +
      'nostrum rerum est autem sunt rem eveniet architecto'
  }
}