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

标签 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. 可以传递到调度操作中的回调:
//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
      })
  );
}
  • 理想情况下,您应该通过 redux actions/reducers 来执行此操作:
  • //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
      }
    }
    

    关于javascript - React/JS - 在操作调用的服务器响应上创建条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52865057/

    相关文章:

    javascript - 在 Electron 中关闭父窗口时防止子窗口关闭

    django - 从 django 传递环境变量以响应应用程序

    javascript - React Native 在静态 navigationOptions 中使用 this.props

    reactjs - 什么是渲染 Prop ,它与高阶组件有何不同?

    javascript - React dropzone 无法使用 axios 发布

    javascript - 从抓取的 HTML 中提取 Javascript 对象的正则表达式

    javascript - html/js : go back to previous page in the same scroll position

    javascript - 使用CSS更改div的背景颜色

    javascript - 使用 Reactjs 的 Axios Post 表单

    javascript - 如何在 Json-server 和 Axios 中使用 delete 方法?