繁体   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