我有一个模态来添加待办事项,待提交后会重置,但如果提交失败也会重置,我该如何使模态保持打开状态并让用户看到他们犯的错误?
//modal component
onSubmit = e => {
e.preventDefault();
const newTask = {
task: this.state.task
};
this.props.addTask(newTask)
// sudo code below
if(this.props.addTask(newTask === 200 status success or something){
this.setState({task: "" })
//Close modal
this.toggle();
}
}
// action file
export const addTask = (task) => dispatch =>{
axios.post('/api/users/newtask', task )
.then(res =>
dispatch({
type: ADD_TASK,
payload: res.data
})
).catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
}
不确定是否有帮助,但是我正在使用axios进行api调用
答案 0 :(得分:1)
您有2种方法:
//modal component
onSubmit = e => {
e.preventDefault();
const newTask = {
task: this.state.task
};
this.props.addTask(newTask, () => {
this.setState({task: "" })
//Close modal
this.toggle();
});
}
// action file
export const addTask = (task, successCallback) => dispatch =>{
axios.post('/api/users/newtask', task )
.then(res => {
dispatch({
type: ADD_TASK,
payload: res.data
});
if (typeof successCallback === 'function') {
successCallback(res.data);
}
)
).catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
}
//modal component (Or don't render the modal at all at the parent component)
...
render() {
if (!this.props.showModal) {
return null;
}
}
// Action:
dispatch({
type: ADD_TASK,
payload: res.data
});
//Reducer
function reducer(state = initialState, action) {
switch (action.type) {
case ADD_TASK:
return Object.assign({}, state, {
tasks: [...state.tasks, action.task],
showModal: false, // <== Set show modal to false when the task is done.
})
default:
return state
}
}