【问题标题】:Redux thunk middleware does not give the required outputRedux thunk 中间件未提供所需的输出
【发布时间】:2022-01-24 21:40:03
【问题描述】:

我是 Redux 新手,正在向 here 学习 redux。
我一直坚持到视频13,所有示例都运行良好。
但是,我无法获得视频编号 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: '' }

实际输出:


截图

我错过了什么?

【问题讨论】:

    标签: javascript node.js redux axios react-thunk


    【解决方案1】:

    store.subscribe(() => { console.log(store.getState()) }) 您在订阅中错过了>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-19
      • 2021-06-05
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      相关资源
      最近更新 更多