所以这是我正在玩
的代码import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import axios from 'axios' const initialState = { user: {}, requesting: false, err: null } const reducer = (state = initialState, action) => { switch (action.type) { case 'REQ_USER_INIT': return { ...state, requesting: true } case 'REQ_USER_DATA': return { ...state, requesting: false, user: action.user } case 'REQ_USER_ERR': return { ...state, requesting: false, err: action.err } } return state; } const logger = (store) => (next) => (action) => { let previous = JSON.stringify(store.getState()) next(action) console.log( 'action: ' + JSON.stringify(action) + '\n\tprevious: ' + previous + '\n\tcurrent: ' + JSON.stringify(store.getState()) ) } const store = createStore(reducer, applyMiddleware(logger, thunk)) store.dispatch((dispatch) => { dispatch({ type: 'REQ_USER_INIT' }) // Fake Online REST API for Testing and Prototyping // break url to get an error response let usersEndpoint = 'https://jsonplaceholder.typicode.com/users/1' axios.get(usersEndpoint) .then((response) => { dispatch({ type: 'REQ_USER_DATA', user: { id: response.data.id, username: response.data.username, email: response.data.email, } }) }) .catch((error) => { dispatch({ type: 'REQ_USER_ERR', err: error.message }) }) })
我相信这很简单,对吧?收到回复后,我会发送REQ_USER_INIT
然后发送REQ_USER_DATA
。我应该记录两个动作,但是我得到3.第二个动作是undefined
我正在努力找出导致它的原因。这是 redux-thunk 的错误还是我做错了什么?
这是我的控制台的输出。
action: {"type":"REQ_USER_INIT"} ·previous: {"user":{},"requesting":false,"err":null} ·current: {"user":{},"requesting":true,"err":null} action: undefined ·previous: {"user":{},"requesting":false,"err":null} ·current: {"user":{},"requesting":true,"err":null} action: {"type":"REQ_USER_DATA","user":{"id":1,"username":"Bret","email":"Sincere@april.biz"}} ·previous: {"user":{},"requesting":true,"err":null} ·current: {"user":{"id":1,"username":"Bret","email":"Sincere@april.biz"},"requesting":false,"err":null}
答案 0 :(得分:37)
中间件的顺序很重要。尝试最后logger
const store = createStore(reducer, applyMiddleware(thunk, logger))