【发布时间】:2021-02-21 15:35:32
【问题描述】:
我正在使用 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”导入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?
【问题讨论】:
标签: react-native async-await react-redux redux-thunk thunk