代码之家  ›  专栏  ›  技术社区  ›  kesarling

Redux thunk中间件未提供所需的输出

  •  1
  • kesarling  · 技术社区  · 3 年前

    here .
    13

    asyncActions.js

    const redux = require('redux')
    const axios = require('axios')
    const thunkMiddleware = require('redux-thunk').default  
    
    const createStore = redux.createStore
    const applyMiddleware = redux.applyMiddleware
    
    const appState = {
        isLoading: false,
        users: [],
        error: "",
    }
    
    const FETCH_USERS_REQUEST = 'FETCH_USERS_REQUEST'
    const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS'
    const FETCH_USERS_FAILURE = 'FETCH_USERS_FAILURE'
    
    const fetchUsersRequest = () => {
        return {
            type: FETCH_USERS_REQUEST,
        }
    }
    
    const fetchUsersSuccess = (users) => {
        return {
            type: FETCH_USERS_SUCCESS,
            payload: users,
        }
    }
    
    const fetchUsersFailure = (error) => {
        return {
            type: FETCH_USERS_FAILURE,
            payload: error,
        }
    }
    
    const fetchUsers = () => {
        return function(dispatch) {
            dispatch(fetchUsersRequest())
            axios.get('https://jsonplaceholder.typicode.com/users')
            .then(response => {
                const users = response.data.map(user => user.id)
                dispatch(fetchUsersSuccess(users))
            })
            .catch(error => {
                dispatch(fetchUsersFailure(error))
            })
        }
    }
    
    const reducer = (state = appState, action) => {
        switch (action.type) {
            case FETCH_USERS_REQUEST:
                return {
                    ...state,
                    isLoading: true,
                }
    
            case FETCH_USERS_SUCCESS:
                return {
                    ...state,
                    isLoading: false,
                    users: action.payload,
                    error: '',
                }
                
            case FETCH_USERS_FAILURE:
                return {
                    ...state,
                    users: [],
                    isLoading: false,
                    error: action.payload,
                }   
        
            default:
                break;
        }
    }
    
    const store = createStore(reducer, applyMiddleware(thunkMiddleware))
    const unSubscribe = store.subscribe(() = { console.log(store.getState()) })
    store.dispatch(fetchUsers())
    unsubscribe() // this statement is not in the tutorial, but I inferred it from the overall tutorial (please tell me if it is required though)
    

    预期产量

    { loading: true, users: [], error: '' }
    { loading: false,
      users: [ 1,2,3,4,5,6,7,8,9,10 ],
      error: '' }
    


    :

    screenshot of the actual output

    我错过了什么?

    1 回复  |  直到 3 年前
        1
  •  1
  •   Saeed Shamloo    3 年前

    store.subscribe(() => { console.log(store.getState()) }) >

    推荐文章