Reactjs Can';无法从array react和Firestore获取数据
如何从数组访问值exist?我想我没有通过里面的阵列?有什么帮助或建议吗Reactjs Can';无法从array react和Firestore获取数据,reactjs,firebase,google-cloud-firestore,Reactjs,Firebase,Google Cloud Firestore,如何从数组访问值exist?我想我没有通过里面的阵列?有什么帮助或建议吗 var isExist = this.props.isFavorite(this.props.code); console.log(isExist) 我有一个变量isExist,它包含下面控制台的响应 [] client: [id: "LvR05w9v9xrC3r4V1W8g", exist: true] length: 1 _proto_:Array(0) 如何访问阵列中的exist?当我尝试isExist[0
var isExist = this.props.isFavorite(this.props.code);
console.log(isExist)
我有一个变量isExist,它包含下面控制台的响应
[]
client: [id: "LvR05w9v9xrC3r4V1W8g", exist: true]
length: 1
_proto_:Array(0)
如何访问阵列中的exist?当我尝试isExist[0]时,发现一个错误。有什么帮助吗
isExist.exist = Undefined
isExist[0].exist = TypeError: Cannot read property 'exist' of undefined
我访问数据并将数据推送到阵列的常用方法
export const isFavorite = (data) => dispatch => {
let exist = [];
var clientQuery = firebase.firestore().collection(path).where('client_id', '==', data);
clientQuery.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
var data = [];
data.id = doc.id;
data.exist = doc.exists;
exist.push(data)
});
});
return exist;
}
您正在创建一个数组对象。然后数组对象{data}[]。所以问题是,数据实际上不仅是一个数组,还是一个对象 试着这样做
var data;
data.id = doc.id;
data.exist = doc.exist;
exist.push(data);
现在您将拥有一个对象数组的现有数据。
然后从它开始迭代
exist[0].id;
//or try
exist[0].data.id;
//Depends on how you implement your data.
isFavorite
返回一个函数,该函数接受一个参数dispatch
并返回exist
数组。您似乎使用异步代码来填充exist
array。因此,当该函数返回时,exist
是一个空数组[]
。您需要继续使用承诺或使用wait
。您需要调用isFavorite
返回的函数
如果
this.props.isFavorite
和const isFavorite
不相同,请添加this.props.isFavorite
的代码。由于客户端数组不包含带有键和值的对象,我建议您尝试使用带有split()的索引数组,以从数组中获取id值和exist值,如
像
这里的change data=[];数组到数据={};反对
querySnapshot.forEach((doc) => {
var data = {};
data.id = doc.id;
data.exist = doc.exists;
exist.push(data)
});
Hi-Aizen,index.js:50未捕获(承诺中)TypeError:无法设置未定义的属性“id”。您不需要临时变量
exist.push({id:doc.id,exist:doc.exists})
Ujin,你是对的,Ujin你不需要。但是Jay Ar是OOP新手,你说不出来吗?当回答问题时,记住Ujin。你需要确保适应他们的编码方式,而不是让他们适应你的。用他们自己的模板回答问题,而不是根据自己的最佳实践重新创建模板。isExist
变量的数据类型是什么?
querySnapshot.forEach((doc) => {
var data = {};
data.id = doc.id;
data.exist = doc.exists;
exist.push(data)
});