0

我有一个简单的减速器。我在 combineReducers 和 createStore 中使用它。我想使用 async thunk 来使用 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;
4

1 回答 1

1

function的第一个参数createAsyncThunktype将生成动作类型。您可以在 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'
  }
}
于 2021-11-02T03:20:37.483 回答