以下代码是我的一个行动,实际上是有效的。
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>
答案 0 :(得分:3)
您不需要await
:
const response = await fetch('<my server url>');
只需要:
const responseJson = await response.json();
这是因为fetch
语句返回Promise
。因此await
仅需要await
Promise
的结果。
这是使用一些模拟函数的简化示例:
// 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;