React-native等待useEffect函数

时间:2020-11-01 18:53:31

标签: firebase react-native google-cloud-firestore react-hooks use-effect

我想从Firestore检索一个字段,但是如何说要等到返回useEffect的函数完成后再返回呢?

这是我的代码:

useEffect(() => {
      handlClick();
  }, []);

  const handlClick = async() => {
    setRestaurant([]);
    db.doc(idBranch).get().then(data => {
        const branchData = data.data();
        setRestaurant(brn => [...brn, branchData]);
    })
  }

  return (
    <View>
        <Text> Name: {restaurant.Name} </Text>
    </View>
  );

1 个答案:

答案 0 :(得分:0)

这段代码可能会有所帮助:

const [isHandleClickCall, setHandleClickCall] = useState(false);

useEffect(() => {
    (async () => {
        await handlClick();
        setHandleClickCall(true);
    })();
}, []);

const handlClick = async () => {
    setRestaurant([]);
    db
        .doc(idBranch)
        .get()
        .then((data) => {
            const branchData = data.data();
            setRestaurant((brn) => [...brn, branchData]);
        });
};

return (
    isHandleClickCall && (
        <View>
            <Text> Name: {restaurant.Name} </Text>
        </View>
    )
);