javascript - 拦截 switch default 或 case 中抛出的错误时的不同行为(React/Redux)

标签 javascript ecmascript-6 redux react-redux

我有这个 reducer 和这两个中间件

...

const reducer  = (
    state = {
        username : '',
        token : '?'
    }, 
    action
) => {
    switch (action.type){
        case 'SET_TOKEN': 
            state = { ...state, token : action.payload }
            break
        case 'SET_USERNAME': 
            state = { ...state, username : action.payload }
            break
        case 'SET_USERNME': 
            throw new Error("Errore, nessuna azione corrispondente")
            break               
    }
    return state
}

const logger = (store) => (next) =>(action) => {

  console.log(store, next, action);
  next(action);

}

const error = (store) => (next) =>(action) => {
  try{
    console.log("Checking errors");
    next(action);
  }catch(e){
    console.log("Error is: " +e);
  }
}

const middleware = applyMiddleware(logger, error);

...

现在,当我向其分派(dispatch)操作“SET_USERNME”时,我的控制台收到错误消息:出现错误,但应用程序继续工作。但我不明白为什么。如果我这样更改开关部分,我将不再收到控制台消息,而是收到错误。

    switch (action.type){
        case 'SET_TOKEN': 
            state = { ...state, token : action.payload }
            break
        case 'SET_USERNAME': 
            state = { ...state, username : action.payload }
            break
        default: 
            throw new Error("Errore, nessuna azione corrispondente")
            break               
    }

最佳答案

问题如下。稍后的实现将针对它不知道的类型的任何操作抛出错误。

创建 store redux 时调度 @@redux/INIT<SomeRandomString> 获得初始状态的 Action 。但是你的 reducer 会抛出失败的整个引导过程。所以你的应用程序根本不会启动。

switch (action.type){
    case 'SET_TOKEN': 
        state = { ...state, token : action.payload }
        break
    case 'SET_USERNAME': 
        state = { ...state, username : action.payload }
        break
    default: // this will throw for redux init action as well.
        throw new Error("Errore, nessuna azione corrispondente")
        break               
}

检查这个comment

/**
 * These are private action types reserved by Redux.
 * For any unknown actions, you must return the current state.
 * If the current state is undefined, you must return the initial state.
 * Do not reference these action types directly in your code.
 */

特别注意对于任何未知的操作,您必须返回当前状态。如果当前状态未定义,您必须返回初始状态。

关于javascript - 拦截 switch default 或 case 中抛出的错误时的不同行为(React/Redux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50367791/

相关文章:

javascript - 主干事件未触发?

javascript - 如何在具有 Ajax 的单个表单中使用多个提交按钮

javascript - 无法使用react-router-dom的WithRouter

javascript - AJAX 列表更新,获取新元素并计数

javascript - 使用 $interval 在 AngularJS 中每秒触发一个 AJAX 请求

javascript - 相当于 ES6 import 中需要一个子属性

javascript - 如何从 Vue.js 中的组件生命周期方法访问 mixin 方法内部的函数

javascript - ES6 类扩展了 Socket IO

reactjs - 用react、redux和promise实现一个confirm组件

reactjs - 使用 ES6 时,导入的函数如何在一个文件中未定义,而在另一个文件中则不然?