我在尝试访问 Firestore 中用户文档的名称字段时遇到问题。每当我 console.log doc.data() 我看到值,但每当我尝试将 doc.data().name 分配给一个变量时,它要么是空的,要么是未定义的。我设置了一个名为“t”的按钮来尝试打印出实际的名称值。关于这里会发生什么的任何想法?
const MessageClickable=(props)=>{
const {userID} = useContext(AuthContext)
const [otherName,setOtherName]=useState()
const [accName, setAccname]= useState([])
let hello=''
useEffect(()=>{
let hello=''
const subscriber=firebase.firestore().collection('Users')
.doc(props.chatMembers[0]==userID ? props.chatMembers[1]:userID)
.get()
.then((doc)=>{
console.log(doc.data())//this succesfully prints out my data
hello=doc.data().name
})
setOtherName(hello)
},[])
const t=()=>{
setOtherName(hello)
console.log(otherName)//this prints out nothing
}
return(
<View >
<Button title="press" onPress={t}/>
<Text></Text>
</View>
)
}
const styles= StyleSheet.create({
container:{
backgroundColor:'blue'
}
})
答案 0 :(得分:0)
get()
方法是异步的,并且返回一个 Promise。此 Promise 使用 get()
方法调用的结果(即 DocumentSnapshot
)解析,并将该结果传递给 then()
处理程序。
因此,只有在 then()
块内才能获得 DocumentSnapshot
的值。
以下应该可以解决问题:
useEffect(() => {
let hello = ''
const subscriber = firebase.firestore().collection('Users')
.doc(props.chatMembers[0]==userID ? props.chatMembers[1]:userID)
.get()
.then((doc) => {
console.log(doc.data())//this succesfully prints out my data
hello = doc.data().name;
setOtherName(hello);
})
},[])
更多解释here,例如。