React / JS-在动作调用的服务器响应上创建条件

时间:2018-10-17 23:44:36

标签: javascript reactjs axios

我有一个模态来添加待办事项,待提交后会重置,但如果提交失败也会重置,我该如何使模态保持打开状态并让用户看到他们犯的错误?

//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调用

1 个答案:

答案 0 :(得分:1)

您有2种方法:

  1. 您可以传递给调度操作的回调:
//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
      })
  );
}
  1. 理想情况下,您应该通过redux动作/减速器执行此操作:

//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
  }
}