【发布时间】:2018-08-26 07:54:04
【问题描述】:
使用 ReactJS、Redux 和 Firestore 创建新记录时出现错误。但是我不明白原因,因为我在 Redux 中正确获取了更新信息,但是在创建记录并返回查看所有记录后,我得到了错误:
TypeError:无法读取未定义的属性“名称”
如果我访问可视化记录一切都很好,问题是当我生成新记录并返回以可视化所有时。
我的 JSON 响应如下:
1:
data: {email: "mail@hotmail.com", lastName: "Asdasd", name: "Oscar"}
uid: "2ts2DopIoXoiMVJ6lMKi"
当我返回获取所有记录并执行 console.log(this.props.clients) 时返回:
0:DocumentReference
firestore:
Firestore {_queue: AsyncQueue, INTERNAL: {…}, _config: FirestoreConfig, _databaseId: DatabaseId, _dataConverter: UserDataConverter, …}
id:(...)
parent:(...)
path:(...)
_firestoreClient:FirestoreClient {platform: BrowserPlatform, databaseInfo: DatabaseInfo, credentials: FirebaseCredentialsProvider, asyncQueue: AsyncQueue, clientId: "BGuRUAvN7ZQxmmNEZmbx", …}
_key:DocumentKey {path: ResourcePath}
__proto__:Object
这是我的代码:
操作:从 Firestore 获取数据
export const getFromFirestore= () => async dispatch => {
let res = [];
await db.collection('users').get().then((snapShot) => {
snapShot.docs.map( doc => {
res.push({ uid: doc.id, data: doc.data()});
})
}, error => {
console.log(error)
});
dispatch({
type: GET_CLIENTS,
payload:res
});
}
减速机:
case GET_CLIENTS:
return{
...state,
clientsFirestore: action.payload
};
客户端组件显示来自 Firestore 的数据:
class Clients extends Component {
componentDidMount(){
this.props.getFromFirestore();
};
deleteClient = (id) => {
this.props.deleteFirestore(id);
}
render() {
const { clients } = this.props;
return (
<React.Fragment>
<h1 className="display-4 mb-2">
<span className="text-danger">Clients</span>
</h1>
<table className="highlight centered">
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
{clients && clients !== undefined ? clients.map((client, key) => (
<Client
key={key}
id={client.uid}
name={client.data.name}
lastName={client.data.lastName}
email={client.data.email }
deleteClient={this.deleteClient}
/>
)): null }
</table>
</React.Fragment>
);
}
}
Clients.propTypes = {
clients: PropTypes.array.isRequired,
}
const mapStateToProps = (state) => ({
clients: state.clients.clientsFirestore
});
export default connect( mapStateToProps, { getFromFirestore, deleteFirestore } )(Clients);
谢谢!
【问题讨论】:
-
根据您的示例,唯一的建议是在
name={client.data.name}client.data中未定义,因此您必须检查您是否正确访问name,或者甚至整个data对象是不需要 -
@KarenGrigoryan 我认为问题在于,当我添加新的 Firestore 记录时,不同数组的第一个元素返回类似:
0:DocumentReference firestore: Firestore {_queue: AsyncQueue, INTERNAL: {…}, _config: FirestoreConfig, _databaseId: DatabaseId, _dataConverter: UserDataConverter, …} id:(...) whrn my array of objects is like: 1: data: {email: "mail@hotmail.com", lastName: "Asdasd", name: "Oscar"} uid: "2ts2DopIoXoiMVJ6lMKi"但我不知道如何获取数据
标签: javascript reactjs firebase google-cloud-firestore