[英]Password value returns undefined, but when console.log is used to display it, the user can see it
[英]Props returns undefined, but I can see its value in the console
我有一個小但令人沮喪的錯誤。 我有一個將組件傳遞給它的孩子的父組件:
const { door } = this.props || []
...
{this.state.showModal ? <ClusterModal door={door} /> : null}
當我想在子組件中訪問它時: this.props.door
。
另外, door
道具還有一個我想訪問的名為doors
的鑰匙。 所以我嘗試了: console.log(this.props.door.doors)
,我的控制台給了我:
無法讀取未定義的屬性“門”
抱歉,這是一個不好解釋的問題,但我無法弄清楚。
謝謝閱讀!
這是父母:
const { door } = this.props
const ifCluster = (
<div>
{door.type === 'cluster' ? (
<div className="door-flex-item-2">
<a
className="sub-title-text-container"
onClick={() => this.toggleModalButton()}
>
Hejsan
</a>
{this.state.showModal ? this.props.door ? (
<ClusterModal door={door} />
) : null : null}
</div>
) : null}
</div>
)
這是孩子:
render() {
// const { door } = this.props || []
const customers = this.props.customers || []
const keyedCustomers = _.keyBy(customers, '_id')
const deliveries = this.props.deliveries || []
const keyedDeliveries = _.keyBy(deliveries, '_id')
console.log(this.props.door)
const clusterDoors = this.props.door.doors.map((clusterDoor, i) => {
console.log(clusterDoor)
我注意到,第一次登錄this.props.door
我得到了數據,但是第二次由於某種原因,它變得undefined
。
將prop值存儲在狀態中,並檢查值是否與prop中的值相同。 用ComponentWillReceiveProps(nextProps)方法執行。
像這樣向組件添加條件
(this.props.door) ? <ClusterModal door={door} /> : <Div/>
因此,只有在門內有價值后才渲染組件
編輯 :
{
(this.state.showModal)
? (this.props.door)
? <ClusterModal door={door} />
: null
: null
}
或者你也可以使用功能
clusterModel = () => { // change according to requirement
if (this.state.showModal) {
if (this.props.door) {
<ClusterModal door={door} />
}
}
}
您將看到錯誤的唯一方法:
無法讀取未定義的屬性“門”
是來自ClusterModal
組件內部的this.props.door.doors
在door
屬性處返回未定義。
這就是const { door } = this.props || []
const { door } = this.props || []
將門設置為未定義。 發生這種情況是因為右側this.props || []
this.props || []
為[]
,並且左側無法進行對象解構,因為您擁有數組,而不是帶有door
鑰匙的對象。
一個快速修復方法是:
const { door } = this.props || { door: { doors: []} }
然后,在您的ClusterModal內部,您將不會收到該錯誤。
在這里,您具有對象和數組解構的規則。
請檢查此內容,因為const { door } = this.props || []
const { door } = this.props || []
沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.