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

在交换机默认或案例中拦截抛出错误时的不同行为(反应/重复)

  •  0
  • DxW  · 技术社区  · 7 年前

    我有这个减速机和这两个中间件

    ...
    
    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);
    
    ...
    

    现在,当我向其发送一个操作“SET\u 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               
        }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Yury Tarabanko    7 年前

    问题如下。稍后的实现将为引发错误 任何 它不知道的类型的操作。

    创建存储时,redux调度 @@redux/INIT<SomeRandomString> 获取初始状态的操作。但您的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.
     */
    

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