簡體   English   中英

道具返回未定義,但我可以在控制台中看到其值

[英]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) ,我的控制台給了我:

在此處輸入圖片說明 太好了! 但是React告訴我這一點:

無法讀取未定義的屬性“門”

抱歉,這是一個不好解釋的問題,但我無法弄清楚。

謝謝閱讀!

編輯

這是父母:

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.doorsdoor屬性處返回未定義。

這就是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM