我正在使用React Native,在挂载之前我必须调用2个Redux thunk(useEffect(。第一个是获取用户位置。第二个给了我一份该地点附近动物的名单。
这是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";;
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 thunk中作为空对象发送,但在状态下加载很好。getLocation返回后,如何使用getAnimals thunk?
getLocation
redux操作不是一个需要等待的常规异步函数。。。它是一个返回函数的函数。。。
所以我建议你在getLocation
redux action 中成功定位后,获得动物列表
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