处理 react redux 中的获取错误的最佳方法是什么?
What is the best way to deal with a fetch error in react redux?
我有一个用于客户端的 reducer,一个用于 AppToolbar,还有一些...
现在假设我创建了一个获取操作来删除客户端,如果它失败了,我在 Clients reducer 中有代码应该做一些事情,但我也想在 AppToolbar 中显示一些全局错误。
但是客户端和 AppToolbar reducers 不共享相同的状态部分,我无法在 reducer 中创建新操作。
那么我应该如何显示全局错误?谢谢
更新 1:
我忘了说我使用 este devstack
更新 2:
我将埃里克的答案标记为正确,但我不得不说我在埃斯特使用的解决方案更像是埃里克和丹的答案的结合......
您只需要在您的代码中找到最适合您的内容...
如果你想拥有"global errors"的概念,你可以创建一个errors
reducer,它可以监听addError、removeError等...动作。然后,您可以在 state.errors
连接到您的 Redux 状态树并在适当的地方显示它们。
有很多方法可以解决这个问题,但一般的想法是全局 errors/messages 值得他们自己的减速器完全独立于 <Clients />
/<AppToolbar />
。当然,如果这些组件中的任何一个需要访问 errors
,您可以在任何需要的地方将 errors
作为道具传递给它们。
更新:代码示例
这是一个示例,说明如果您将 "global errors" errors
传递到顶层 <App />
并有条件地渲染它(如果存在错误) ).使用 react-redux's connect
将您的 <App />
组件连接到某些数据。
// App.js
// Display "global errors" when they are present
function App({errors}) {
return (
<div>
{errors &&
<UserErrors errors={errors} />
}
<AppToolbar />
<Clients />
</div>
)
}
// Hook up App to be a container (react-redux)
export default connect(
state => ({
errors: state.errors,
})
)(App);
而对于 action creator 而言,它会根据响应分派 (redux-thunk) 次成功失败
export function fetchSomeResources() {
return dispatch => {
// Async action is starting...
dispatch({type: FETCH_RESOURCES});
someHttpClient.get('/resources')
// Async action succeeded...
.then(res => {
dispatch({type: FETCH_RESOURCES_SUCCESS, data: res.body});
})
// Async action failed...
.catch(err => {
// Dispatch specific "some resources failed" if needed...
dispatch({type: FETCH_RESOURCES_FAIL});
// Dispatch the generic "global errors" action
// This is what makes its way into state.errors
dispatch({type: ADD_ERROR, error: err});
});
};
}
虽然您的减速器可以简单地管理一系列错误,但 adding/removing 个条目是适当的。
function errors(state = [], action) {
switch (action.type) {
case ADD_ERROR:
return state.concat([action.error]);
case REMOVE_ERROR:
return state.filter((error, i) => i !== action.index);
default:
return state;
}
}
是正确的,但我想补充一点,您不必为添加错误而触发单独的操作。另一种方法是使用一个 reducer 来处理 任何带有 error
字段 的操作。这是个人选择和约定的问题。
例如,来自具有错误处理的 Redux real-world
example:
// Updates error message to notify about the failed fetches.
function errorMessage(state = null, action) {
const { type, error } = action
if (type === ActionTypes.RESET_ERROR_MESSAGE) {
return null
} else if (error) {
return error
}
return state
}
我目前针对一些特定错误(用户输入验证)采用的方法是让我的子化简器抛出异常,在我的根化简器中捕获它,并将其附加到操作对象。然后我有一个 redux-saga,它检查动作对象是否有错误,并在这种情况下用错误数据更新状态树。
所以:
function rootReducer(state, action) {
try {
// sub-reducer(s)
state = someOtherReducer(state,action);
} catch (e) {
action.error = e;
}
return state;
}
// and then in the saga, registered to take every action:
function *errorHandler(action) {
if (action.error) {
yield put(errorActionCreator(error));
}
}
然后按照 Erik 的描述将错误添加到状态树。
我很少使用它,但它使我不必复制合法属于减速器的逻辑(因此它可以保护自己免受无效状态的影响)。
您可以使用 axios HTTP 客户端。它已经实现了拦截器功能。您可以在请求或响应被 then 或 catch 处理之前拦截它们。
https://github.com/mzabriskie/axios#interceptors
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
编写自定义中间件来处理所有 api 相关错误。在这种情况下,您的代码会更简洁。
failure/ error actin type ACTION_ERROR
export default (state) => (next) => (action) => {
if(ACTION_ERROR.contains('_ERROR')){
// fire error action
store.dispatch(serviceError());
}
}
我所做的是在每个效果的基础上集中处理效果中的所有错误
/**
* central error handling
*/
@Effect({dispatch: false})
httpErrors$: Observable<any> = this.actions$
.ofType(
EHitCountsActions.HitCountsError
).map(payload => payload)
.switchMap(error => {
return of(confirm(`There was an error accessing the server: ${error}`));
});
我有一个用于客户端的 reducer,一个用于 AppToolbar,还有一些...
现在假设我创建了一个获取操作来删除客户端,如果它失败了,我在 Clients reducer 中有代码应该做一些事情,但我也想在 AppToolbar 中显示一些全局错误。
但是客户端和 AppToolbar reducers 不共享相同的状态部分,我无法在 reducer 中创建新操作。
那么我应该如何显示全局错误?谢谢
更新 1:
我忘了说我使用 este devstack
更新 2: 我将埃里克的答案标记为正确,但我不得不说我在埃斯特使用的解决方案更像是埃里克和丹的答案的结合...... 您只需要在您的代码中找到最适合您的内容...
如果你想拥有"global errors"的概念,你可以创建一个errors
reducer,它可以监听addError、removeError等...动作。然后,您可以在 state.errors
连接到您的 Redux 状态树并在适当的地方显示它们。
有很多方法可以解决这个问题,但一般的想法是全局 errors/messages 值得他们自己的减速器完全独立于 <Clients />
/<AppToolbar />
。当然,如果这些组件中的任何一个需要访问 errors
,您可以在任何需要的地方将 errors
作为道具传递给它们。
更新:代码示例
这是一个示例,说明如果您将 "global errors" errors
传递到顶层 <App />
并有条件地渲染它(如果存在错误) ).使用 react-redux's connect
将您的 <App />
组件连接到某些数据。
// App.js
// Display "global errors" when they are present
function App({errors}) {
return (
<div>
{errors &&
<UserErrors errors={errors} />
}
<AppToolbar />
<Clients />
</div>
)
}
// Hook up App to be a container (react-redux)
export default connect(
state => ({
errors: state.errors,
})
)(App);
而对于 action creator 而言,它会根据响应分派 (redux-thunk) 次成功失败
export function fetchSomeResources() {
return dispatch => {
// Async action is starting...
dispatch({type: FETCH_RESOURCES});
someHttpClient.get('/resources')
// Async action succeeded...
.then(res => {
dispatch({type: FETCH_RESOURCES_SUCCESS, data: res.body});
})
// Async action failed...
.catch(err => {
// Dispatch specific "some resources failed" if needed...
dispatch({type: FETCH_RESOURCES_FAIL});
// Dispatch the generic "global errors" action
// This is what makes its way into state.errors
dispatch({type: ADD_ERROR, error: err});
});
};
}
虽然您的减速器可以简单地管理一系列错误,但 adding/removing 个条目是适当的。
function errors(state = [], action) {
switch (action.type) {
case ADD_ERROR:
return state.concat([action.error]);
case REMOVE_ERROR:
return state.filter((error, i) => i !== action.index);
default:
return state;
}
}
error
字段 的操作。这是个人选择和约定的问题。
例如,来自具有错误处理的 Redux real-world
example:
// Updates error message to notify about the failed fetches.
function errorMessage(state = null, action) {
const { type, error } = action
if (type === ActionTypes.RESET_ERROR_MESSAGE) {
return null
} else if (error) {
return error
}
return state
}
我目前针对一些特定错误(用户输入验证)采用的方法是让我的子化简器抛出异常,在我的根化简器中捕获它,并将其附加到操作对象。然后我有一个 redux-saga,它检查动作对象是否有错误,并在这种情况下用错误数据更新状态树。
所以:
function rootReducer(state, action) {
try {
// sub-reducer(s)
state = someOtherReducer(state,action);
} catch (e) {
action.error = e;
}
return state;
}
// and then in the saga, registered to take every action:
function *errorHandler(action) {
if (action.error) {
yield put(errorActionCreator(error));
}
}
然后按照 Erik 的描述将错误添加到状态树。
我很少使用它,但它使我不必复制合法属于减速器的逻辑(因此它可以保护自己免受无效状态的影响)。
您可以使用 axios HTTP 客户端。它已经实现了拦截器功能。您可以在请求或响应被 then 或 catch 处理之前拦截它们。
https://github.com/mzabriskie/axios#interceptors
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
编写自定义中间件来处理所有 api 相关错误。在这种情况下,您的代码会更简洁。
failure/ error actin type ACTION_ERROR
export default (state) => (next) => (action) => {
if(ACTION_ERROR.contains('_ERROR')){
// fire error action
store.dispatch(serviceError());
}
}
我所做的是在每个效果的基础上集中处理效果中的所有错误
/**
* central error handling
*/
@Effect({dispatch: false})
httpErrors$: Observable<any> = this.actions$
.ofType(
EHitCountsActions.HitCountsError
).map(payload => payload)
.switchMap(error => {
return of(confirm(`There was an error accessing the server: ${error}`));
});