我正在使用React Native,必须在挂载(useEffect)之前调用2个Redux thunk。第一个是获取用户位置。第二个给了我该地点附近的动物名单。
这是Thunk的位置(useLocation是一个自定义钩子):
export const getLocation = () => async (dispatch) => {
await useLocation()
.then((res) => {
dispatch(getLocationSuccess(res));
})
.catch((err) => {
console.log(err, "ERROR");
});
};
这很好用。
这是动物的重击:
export const getAnimals = (data) => async (dispatch) => {
await api.animals
.list(data)
.then((res) => {
dispatch(getLostsSuccess(res.data));
})
.catch((err) => {
console.log(err)
});
};
这是Api助手:
从“ axios”导入axios;
const requestHelper = axios.create({
baseURL: "http://192.168.0.15:8000/api/",
headers: {
"Content-Type": "application/json",
},
});
const routes = {
animals: {
list: (data) =>
requestHelper({
data,
method: "post",
url: "animals/list/",
}),
};
export default routes;
这是组件(useEffect和async):
useEffect(() => {
asyncEffect()
}, []);
const asyncEffect = async () => {
const location = await getLocation();
getAnimals({ location: location, status: 1 });
};
“位置”在getAnimals中作为空对象发送,但是在状态加载时就可以了。在getLocation返回后如何使用getAnimals thunk?
答案 0 :(得分:0)
getLocation
redux-action不是要等待的常规异步函数,而是返回函数的函数...
因此,我建议您在getLocation
redux动作中成功找到位置后,获得动物名单
export const getLocation = () => async (dispatch) => {
await useLocation()
.then((res) => {
dispatch(getLocationSuccess(res));
/**
* call getAnimals here // <<--
*/
})
.catch((err) => {
console.log(err, "ERROR");
});
};
const asyncEffect = async () => {
const location = await getLocation();
// getAnimals({ location: location, status: 1 });
};
如果要一次调用getAnimals
/** Executes only on app-mount */
useEffect(() => {
getLocation();
}, []);
useEffect(() => {
if (location) {
// get animals here
getAnimals({ location: location, status: 1 });
}
}, [location]); // location is pulled from redux-store using mapStateToProps