从 Firestore 获取文档数据后无法设置状态

Unable to set state after getting document data from Firestore

我正在尝试创建用户配置文件页面,但在从 Firestore 获取数据后,我无法将数据设置为 userProfile 状态。

  const {userProfile, setUserProfile} = useState(null);

  const getUserProfile = async () => {
    await firestore().collection("Users")
    .doc(user.uid)
    .get()
    .then(documentSnapshot => {
      if (documentSnapshot.exists) {
        console.log('User data from Firestore: ', documentSnapshot.data());
        setUserProfile(documentSnapshot.data());
      }
    });    
  }

  useEffect (() => {
    if (userProfile == null) {
      getUserProfile();
      console.log("User Data in userProfile state: ", userProfile);
    }
  }, [userProfile]) 

我收到这个错误:

控制台日志显示 userProfile 状态未定义,但是,我可以从 Firestore 检索数据,没有任何问题,如控制台日志中所示。

const {userProfile, setUserProfile} = useState(null); <----- error is here

  const getUserProfile = async () => {
    await firestore().collection("Users")
    .doc(user.uid)
    .get()
    .then(documentSnapshot => {
      if (documentSnapshot.exists) {
        console.log('User data from Firestore: ', documentSnapshot.data());
        setUserProfile(documentSnapshot.data());
      }
    });    
  }

  useEffect (() => {
    if (userProfile == null) {
      getUserProfile();
      console.log("User Data in userProfile state: ", userProfile);
    }
  }, [userProfile]) 

而不是const {userProfile, setUserProfile} = useState(null);

替换为const [userProfile, setUserProfile] = useState(null);

因为你正在使用 curly brackets{userProfile,setUserProfile}

你需要用 square brackets[userProfile,setUserProfile]