【问题标题】:react.js: Create resource with redux-form, rest api and async/awaitreact.js:使用 redux-form、rest api 和 async/await 创建资源
【发布时间】:2018-07-05 03:14:39
【问题描述】:

我正在尝试使用 redux 表单和 REST api 创建新资源。

我发送createPost 操作,我想在继续之前检查帖子是否成功。

const handleFormSubmit = (values, dispatch) => {
    dispatch(createPost(values));
    //I want to check here if post was succeeded.
    //if status = 200 this.props.history.push('/');
}


export function createPost(values) {
  return async function(dispatch) {
    let request;
    try {
      request = await axios.post(`${ROOT_URL}/posts`, values)
    } catch(err) {
      request = { err };
    }
    dispatch({
      type: CREATE_POST,
      payload: request
    })    
  }
}

【问题讨论】:

    标签: javascript reactjs redux redux-form redux-thunk


    【解决方案1】:

    返回一个承诺,像这样:

    export function createPost(values) {
      return function(dispatch) {
        return new Promise( async function(resolve, reject){
          let request;
          try {
            request = await axios.post(`${ROOT_URL}/posts`, values)
          } catch(err) {
            reject(err)
          }
          dispatch({
            type: CREATE_POST,
            payload: request
          }) 
          resolve(request)
        })
      }   
    }
    
       const handleFormSubmit = () => {
            dispatch(createPost(values))
            .then( res => {
              // do yoour stuff on succes
            } )
            .catch(err => {
              // stuff on err
            }) 
        }
    

    【讨论】:

      【解决方案2】:

      看到您的代码,我认为您不需要使用承诺。 请尝试如下:

      const getAction = (values) => (dispatch) => {
        return axios
                .post(`${ROOT_URL}/posts`, values)
                .then(
                  () => {
                    dispatch({
                      type: CREATE_POST,
                      payload: request
                    })
                  },
                  () => {
                    throw new SubmissionError({
                      _error: 'Failed'
                    });
                  }
                 );
      };
      
      const handleSubmit = (values) => {
        return dispatch(getAction(values));
      };

      【讨论】:

        猜你喜欢
        • 2012-09-23
        • 2020-06-22
        • 1970-01-01
        • 2017-09-06
        • 1970-01-01
        • 1970-01-01
        • 2019-09-09
        • 2018-06-24
        • 2021-09-11
        相关资源
        最近更新 更多