javascript - 为什么 ASYNC AWAIT 在反应中的使用效果不好
问题描述
我试图获取用户位置,然后使用该位置返回相关数据以获取位置。
但是在第二个函数中,我得到位置为空(当我 console.log(location) 它打印正确的位置,在第二个打印时,第一个打印为空)似乎第二个函数没有等到第一个一个完成了。
这是一些代码:
从组件
const location = useSelector(state => state.locationReducer.location);
useEffect(()=> {
(async () => {
await getLocation();
// here i'm using the location from the first function
await getInfo(location);
})()
}, []);
const getLocation = async() => {
try {
await dispatch(getLocation());
console.log(location);
} catch (err) {
// TODO HANDLE ERROR;
console.log('Err:', err);
}
}
在行动中
export const getLocation = locationName => {
return async dispatch => {
try {
const location = **await** locationService.getLocation(locationName);
**await** dispatch(setLocation(location));
} catch (err) {
throw err;
};
};
};
const setLocation = location => {
return {
type: types.SET_LOCATION,
location
};
};
在役
async function getLocation(locationName) {
try {]
return **await** axios.get(`${url}/${locationName}`);
} catch (err) {
throw err
};
};
解决方案
在您的第一个函数运行后和第二个函数之前,选择器中的location
值不会更新,因此您会在location
变量中看到旧值。
您可能需要从减速器返回您的位置值:
export const getLocation = locationName => {
return async dispatch => {
try {
const location = await locationService.getLocation(locationName);
await dispatch(setLocation(location));
return location;
} catch (err) {
throw err;
};
};
};
并使用您的返回位置useEffect
:
useEffect(()=> {
(async () => {
const location = await getLocation();
// here i'm using the location from the first function
await getInfo(location);
})()
}, []);
或另一种可能性,以产生另一种效果,这取决于位置值:
const location = useSelector(state => state.locationReducer.location);
useEffect(()=> {
getLocation();
}, []);
useEffect(()=> {
if(location) {
getInfo(location);
}
}, [location]);
这将在每次位置更改时运行,并且位置具有一定的价值。
推荐阅读
- arrays - 连接不同大小的数组
- angular - Checkmarx 和 angular2 模板 xss 警告
- python - 模拟真实点击python
- idris - Idris2:相关总和类型区分
- discord.js - 当我使用我的不和谐机器人运行命令时出现错误
- javascript - Pug js 自定义过滤器
- tags - 赛普拉斯黄瓜标签在 Windows 10 中不起作用
- python - 如何在 tensorflow 2.0 中保存和恢复自定义的 seq2seq 模型?
- node.js - nodejs 和 sequelize 迁移收到错误消息
- python - 更新函数返回错误并且不更新数据