如何归还反应重做的动作创作者的承诺?

问题描述 投票:0回答:1

我试图从 复活动作创造者. 但我越来越 未定义.

组件.js

componentDidMount = () => {

   this
       .props
       .getMyData()
       .then(responseFromAction => {
           console.log("Response from Action :", responseFromAction)
        })
       .catch(err => {
           console.log("catch->", err)
       })
}

控件.js

export const getMyData = () => {

  return async (dispatch, getState) => {

     return new Promise((resolve, reject) => {

        axios
          .get(
               API_URL
          )
          .then(async res => {
               if(res.data.success) {
                  const payload = res.data.myData;

                  dispatch({
                     type : SET_MY_DATA,
                     payload,
                  });

                  resolve(res.data.myData.length);

                }
                else {
                   reject();
                }
            })
            .catch(err => {
                reject()
            })   
        })
    }
}

我想我应该从服务器获取一个数据数组的长度,但我得到的却是''。未定义'在component.js中

javascript reactjs react-native redux promise
1个回答
1
投票

通过在动作创建者的内部函数中使用async关键字,你实际上是在返回诺言作为对 .then 的getMyData。

您可以通过删除异步关键字来轻松解决您的问题。

export const getMyData = () => {

  return (dispatch, getState) => {

     return new Promise((resolve, reject) => {

        axios
          .get(
               API_URL
          )
          .then(async res => {
               if(res.data.success) {
                  const payload = res.data.myData;

                  dispatch({
                     type : SET_MY_DATA,
                     payload,
                  });

                  resolve(res.data.myData.length);

                }
                else {
                   reject();
                }
            })
            .catch(err => {
                reject()
            })   
        })
    }
}

或者如果你选择使用async关键字,也许你可以在内部承诺中使用 await,然后返回值。

export const getMyData = () => {

  return async (dispatch, getState) => {

     const length = await new Promise((resolve, reject) => {

        axios
          .get(
               API_URL
          )
          .then(async res => {
               if(res.data.success) {
                  const payload = res.data.myData;

                  dispatch({
                     type : SET_MY_DATA,
                     payload,
                  });

                  resolve(res.data.myData.length);

                }
                else {
                   reject();
                }
            })
            .catch(err => {
                reject()
            })   
        });

       return length;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.