【问题标题】:How to use createThunkAsync without createSlice如何在没有 createSlice 的情况下使用 createThunkAsync
【发布时间】:2021-12-14 16:59:50
【问题描述】:

我有一个简单的减速器。我在 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;

【问题讨论】:

    标签: javascript redux redux-thunk redux-toolkit react-thunk


    【解决方案1】:

    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'
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2019-11-15
      • 2013-06-30
      • 2015-08-09
      • 2018-08-21
      • 2017-06-11
      • 2017-12-02
      • 2014-06-24
      • 2019-01-24
      相关资源
      最近更新 更多