redux-thunk和async / await动作:如何将它们全部组合起来?

时间:2017-11-01 08:17:15

标签: reactjs react-native async-await redux-thunk

以下代码是我的一个行动,实际上是有效的。

export const loadChannelList = () => { 
    return async (dispatch) => {

        dispatch ({
            type: CHANNEL_LIST_LOADING
        });

        try {
            const response  = await fetch('<my server url>');
            const responseJson = await response.json();

            dispatch ({
                type: CHANNEL_LIST_LOADING_OK,
                payload: "ok" // response.json()
            });

        } catch(error) {
            dispatch ({
                type: CHANNEL_LIST_LOADING_FAILED,
                payload: error
            });
        }
    };
}

在组件中,我以这种方式使用它:

componentWillReceiveProps(nextProps) {
        if (this.props.connectionStatus != 'ok' 
            && nextProps.connectionStatus == 'ok'
           ) {
            this.props.loadChannelList();
        }
}

我问你:这是在玩redux-thunk时使用async / await的正确方法吗?

我问这个是因为这是我第一次在redux-thunk动作中的react-native应用程序中使用async / await而且我想确定我没有做一些反模式或其他错误< / p>

1 个答案:

答案 0 :(得分:3)

您不需要await

const response  = await fetch('<my server url>');

只需要:

const responseJson = await response.json();

这是因为fetch语句返回Promise。因此await仅需要await Promise的结果。

这是使用一些模拟函数的简化示例:

&#13;
&#13;
// A fake asynchronous request
function fetch(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        data: x
      });
    }, 3000);
  });
}

// A fake Dispatch function
function fakeDispatch(theData) {
  console.log(theData);
}

// A function to run on componentDidMount or similar
async function getData(x) {
  const response = fetch(x);
  
  // call the Dispatch
  fakeDispatch(await response);
}

// componentDidMount
console.log('Mounting component...');
getData("some data");
&#13;
&#13;
&#13;