【问题标题】:how to set callback of post request in react with redux, redux-thunk and axios?如何设置 post 请求的回调以响应 redux、redux-thunk 和 axios?
【发布时间】:2017-10-08 17:37:07
【问题描述】:

我正在尝试执行异步发布请求以仅在成功后更新我的数据。

我想要的是在行动调用中使用承诺类型的东西。

this.props.postAction('/event/user/44/post',data)
.then((response) =>{
  console.log("Inside callback"); 
  console.log(response);
});
export default connect({postAction})(EventFeed);

这是我正在发出发布请求的操作文件

export const POST_ACTION = 'POST_ACTION';

export function postAction(url,data) {
  return function(dispatch) {
      axios({
          method:'post',
          url:API_URL + url,
          headers: {'event': 55},
          data: data,
      })
    .then(response => {
      dispatch({
        type: POST_ACTION,
        payload: response.data
      });
    })
    .catch((error) => {
      console.log(error);
    })
  }
}

但我永远不会进入回调。

现在如何进行回调以从响应中获取数据???

【问题讨论】:

    标签: api reactjs redux axios redux-thunk


    【解决方案1】:

    首先,你不应该。你违反了Unidirectional dataflow 背后的整个想法。当使用 Redux 时,你的异步内容应该在 action creator 中单独处理,它使用潜在的数据负载分派 action,更新 store 并重新渲染应用程序。当您通过承诺链伸出并“返回”时,您就违反了该流程。

    有了这个警告,你并没有从你的 thunk 中返回承诺。您还应该在链接 then 时返回您的响应。 MDN

    export function postAction(url,data) {
      return function(dispatch) {
          //You need to return your promise.
          return axios({
              method:'post',
              url:API_URL + url,
              headers: {'event': 55},
              data: data,
          })
        .then(response => {
          dispatch({
            type: POST_ACTION,
            payload: response.data
          });
          return response;
        })
        .catch((error) => {
          console.log(error);
        })
      }
    }
    

    也许https://codereview.stackexchange.com/ 是解决这类问题的更好地方。

    【讨论】:

      【解决方案2】:

      您好,您可以将回调函数作为参数传递给 redux 操作

      export const createUser = (user, callBack) => {
          api.defaults.headers.common['Authorization'] = state.token.token;
          api.post("/users/create", user)
              .then(response => {
                  //dispach(createUserSuccess(response.data));
                  if (callBack !== undefined) {
                      callBack(response.data, null);
                  }
              }).catch(error => {
                  error = errorManager(error);
                  //dispach(createUserFailure(error));
                  if (callBack !== undefined) {
                      callBack(null, error);
                  }
              });
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-30
        • 2018-12-02
        • 2018-03-19
        • 2019-08-05
        • 2021-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多