【问题标题】:React Native Calling async function and use return in another async functionReact Native 调用异步函数并在另一个异步函数中使用 return
【发布时间】: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


    【解决方案1】:

    getLocationredux-action 不是要等待的常规异步函数……它是一个返回函数的函数……

    所以我建议你在getLocationredux 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
    

    【讨论】:

    • 您好!感谢您的回答。我将以多种方式和多个组件使用“useLocation()”。这就是我将它添加到 redux 商店的原因。所以我不希望每次调用“useLocation”时都会调用 getAnimals。有没有别的办法单独调用?
    猜你喜欢
    • 2017-08-13
    • 2017-07-20
    • 1970-01-01
    • 2022-01-25
    • 2020-09-18
    • 1970-01-01
    • 2020-03-04
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多