gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:52:20 25 4
gpt4 key购买 nike

我有这个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com