gpt4 book ai didi

javascript - ReactJS: TypeError: 无法读取未定义的属性 'name'

转载 作者:行者123 更新时间:2023-12-03 01:15:47 24 4
gpt4 key购买 nike

使用 ReactJS、Redux 和 Firestore 创建新记录时出现错误。但是我不明白原因,因为我在 Redux 中正确获取了更新的信息,但在创建记录并返回查看所有记录后,我收到错误:

类型错误:无法读取未定义的属性“名称”

如果我访问可视化记录,一切都很好,问题是当我生成新记录并返回可视化所有记录时。

我的 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
});
}

reducer :

    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 的属性

检查下面的代码

{clients && clients != undefined ? clients.map((client, key) => (
{client && client != undefined && client.data && (<Client
key={key}
id={client.uid && client.uid }
name={client.data.name && client.data.name}
lastName={client.data.lastName && client.data.lastName}
email={client.data.email && client.data.email }
deleteClient={this.deleteClient}
/>)}
)): null }

PS:- 当您发布此类问题时,请尝试发布 json 数据以快速找到解决方案

关于javascript - ReactJS: TypeError: 无法读取未定义的属性 'name',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52024282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com