Reactjs redux thunk和异步/等待操作:如何将它们结合起来?
下面的一段代码是我的一项操作,实际上是有效的Reactjs redux thunk和异步/等待操作:如何将它们结合起来?,reactjs,react-native,async-await,redux-thunk,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&
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
});
}
};
}
我问你:在玩redux thunk时,这是使用async/await的正确方法吗
我这样问是因为这是我第一次在react原生应用程序中以redux thunk动作使用async/await,我希望确保我没有出现反模式或其他错误您不需要在以下方面使用await:
这是因为fetch语句返回一个承诺。所以等待只是等待承诺的结果
下面是使用一些模拟函数的简化示例:
//伪异步请求
函数fetchx{
返回新PromiseSolve=>{
设置超时=>{
决心{
数据:x
};
}, 3000;
};
}
//假调度函数
函数fakeDispatchtheData{
console.logtheData;
}
//在componentDidMount或类似设备上运行的函数
异步函数getDatax{
const response=fetchx;
//打电话给调度
假调度等待响应;
}
//组件安装
控制台。记录“安装组件…”;
获取数据集数据 您不需要等待:
这是因为fetch语句返回一个承诺。所以等待只是等待承诺的结果
下面是使用一些模拟函数的简化示例:
//伪异步请求
函数fetchx{
返回新PromiseSolve=>{
设置超时=>{
决心{
数据:x
};
}, 3000;
};
}
//假调度函数
函数fakeDispatchtheData{
console.logtheData;
}
//在componentDidMount或类似设备上运行的函数
异步函数getDatax{
const response=fetchx;
//打电话给调度
假调度等待响应;
}
//组件安装
控制台。记录“安装组件…”;
获取数据集数据;我觉得不错。你觉得奇怪吗?@Davintroon我问这个问题是因为这是我第一次在react原生应用程序中以redux thunk动作使用async/await,我想确定我没有做一些反模式或其他操作errors@DavinTryon:没有其他人回复。请将您的评论转换为答案,我将接受它,不需要等待const response=await fetch;。仅在const responseJson=wait response.json上;我觉得不错。你觉得奇怪吗?@Davintroon我问这个问题是因为这是我第一次在react原生应用程序中以redux thunk动作使用async/await,我想确定我没有做一些反模式或其他操作errors@DavinTryon:没有其他人回复。请将您的评论转换为答案,我将接受它,不需要等待const response=await fetch;。仅在const responseJson=wait response.json上;
componentWillReceiveProps(nextProps) {
if (this.props.connectionStatus != 'ok'
&& nextProps.connectionStatus == 'ok'
) {
this.props.loadChannelList();
}
}
const response = await fetch('<my server url>');
const responseJson = await response.json();