【问题标题】:Redux reducer not showing my console log and returning undefinedRedux reducer 不显示我的控制台日志并返回 undefined
【发布时间】:2020-06-07 00:08:50
【问题描述】:

您好,自从我将 JWT 添加到我的 Nest API 后,我的 Redux 应用程序出现了问题, 这是我的减速器的代码:

export default function reducer(state = {}, action) {
    switch (action.type) {
      case 'USER_LOGIN_SUCCESS':
        console.log('USER_LOGIN_SUCCESS')
        return action.payload.user;
      case 'USER_REGISTER_SUCCESS':
        // user exist
        if(action.payload.status === 409){
            console.log(action.payload)
            return state;
        }
        console.log(action.payload)
        return state
      case 'USER_REGISTER_FAILURE':
      case 'USER_LOGIN_FAILURE':
      default:
        console.log('lol');
        return state
    }
  }

当我使用 redux-api-middleware 登录我的 API 时,这就是我在控制台中得到的:

redux.js:463 Uncaught (in promise) Error: Given action "USER_LOGIN_SUCCESS", reducer "user" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.
    at combination (redux.js:463)
    at dispatch (redux.js:213)
    at _callee$ (index.umd.js:2874)
    at s (index.js:1)
    at Generator._invoke (index.js:1)
    at Generator.e.<computed> [as next] (index.js:1)
    at asyncGeneratorStep (index.umd.js:33)
    at _next (index.umd.js:55)

当我用 POSTMAN 尝试我的请求时,它运行良好:/ 问题是它甚至没有在我的减速器案例中显示 console.log:'USER_LOGIN_SUCCESS'

这是对 POSTMAN 的请求响应: POSTMAN RESPONSE

【问题讨论】:

  • 也许这与问题无关,但尽量避免在 reducer 中那些只是缺少 return 语句的情况。鉴于 USER_REGISTER_FAILUREUSER_LOGIN_FAILURE 没有返回任何内容。即使返回null也比没有好。

标签: javascript reactjs redux next.js


【解决方案1】:

在您的 USER_LOGIN_SUCCESS 情况下,您将返回操作负载值。

使用 reducer,您必须始终返回状态对象或状态对象的不可变副本。

不清楚你的减速器状态对象是什么样的,但我认为它包含一个用户属性

return {
  ...state,
  user: action.payload.user
}

【讨论】:

  • 感谢它完美地工作,我已经尝试过创建一个 newState 并返回它,但它没有工作,再次感谢:D!
猜你喜欢
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
相关资源
最近更新 更多