If you want to have the concept of "global errors", you can create an errors
reducer, which can listen for addError, removeError, etc... actions. Then, you can hook into your Redux state tree at state.errors
and display them wherever appropriate.
There are a number of ways you could approach this, but the general idea is that global errors/messages would merit their own reducer to live completely separate from <Clients />
/<AppToolbar />
. Of course if either of these components needs access to errors
you could pass errors
down to them as a prop wherever needed.
Update: Code Example
Here is one example of what it might look like if you were to pass the "global errors" errors
into your top level <App />
and conditionally render it (if there are errors present). Using react-redux's connect
to hook up your <App />
component to some data.
// 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);
And as far as the action creator is concerned, it would dispatch (redux-thunk) success failure according to the response
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});
});
};
}
While your reducer could simply manage an array of errors, adding/removing entries appropriately.
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;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…