Problem Overview
The following is a standard way to send error / success messages , at least for what the tutorials recommend:
{ type: 'FETCH_POSTS_FAILURE', error: 'Oops' }
{ type: 'FETCH_POSTS_SUCCESS', success: 'yay', response: { ... } }
{ type: 'FETCH_POSTS', status: 'error', error: 'Oops' }
{ type: 'FETCH_POSTS', status: 'success', response: { ... } }
However, the problem that I encountered is that these error / success messages will be displayed inside the EVERY component listening for a specific reducerthat handles these actions.
Example script:
You have a todo application in which there are three add , modify and delete actions, but all three of these actions are performed from separate pages from the point of view of the user interface. And they are all processed by the same todo gearbox .
Also, all components that provide an interface for triggering these actions listen on this todo reducer via mapStateToProps to receive changes todo (not applicable to this example) and success and error messages :
function mapStateToProps(state) {
return {
success: state.todo.success,
error: state.todo.error,
};
}
{!!this.props.success && <p>{this.props.success}</p>}
{!!this.props.error && <p>{this.props.error}</p>}
, theres todo, todo todo.
, todo , todo todo, 3 : state.todo.error.
, . /, .
1: , /
, / - . , , :
const status = combineReducers({
add_todo, // handles error/success for add_todo
edit_todo, // handles error/success for edit_todo
delete_todo, // handles error/success for delete_todo
…
update_bio, // handles error/success for update_bio
etc...
});
/ :
function mapStateToProps(state) {
return {
error: state.status.add_todo.error,
success: state.status.add_todo.success
};
}
{!!this.props.error && <p>{this.props.error}</p>}
{!!this.props.success && <p>{this.props.success}</p>}
....
function mapStateToProps(state) {
return {
error: state.status.edit_todo.error,
success: state.status.edit_todo.success
};
}
{!!this.props.error && <p>{this.props.error}</p>}
{!!this.props.success && <p>{this.props.success}</p>}
, , , , ?
2: / ,
. todo :
ADD_TODO_FAILED:
return {...state, error_add_todo: action.error }
EDIT_TODO_FAILED:
return {...state, error_edit_todo: action.error }
DELETE_TODO_FAILED:
return {...state, error_delete_todo: action.error }
/ :
function mapStateToProps(state) {
return {
error: state.todo.error_add_todo,
success: state.todo.success_add_todo
};
}
{!!this.props.error && <p>{this.props.error}</p>}
{!!this.props.success && <p>{this.props.success}</p>}
....
function mapStateToProps(state) {
return {
error: state.todo.error_edit_todo,
success: state.todo.success_edit_todo
};
}
{!!this.props.error && <p>{this.props.error}</p>}
{!!this.props.success && <p>{this.props.success}</p>}
, , / .
stateMapToProps , , state.todo.error
, error
, .
, , , - , , ?
2 , ?
!