简体   繁体   English

反应-无法设置未定义的属性

[英]React - Cannot set property of undefined

I have a React component that uses querySelectorAll to get the value of elements on the page then renders them in the component. 我有一个React组件,该组件使用querySelectorAll获取页面上元素的值,然后在组件中呈现它们。 With the code below I am getting the error 'Cannot set property of 'label1' of undefined', but i'm not sure why as it's finding the value correctly using the querySelector and this.label1 is a global variable. 在下面的代码中,我收到错误消息“无法设置未定义的'label1'的属性',但是我不确定为什么要使用querySelector正确找到该值,而this.label1是全局变量。

import React from 'react'

class StickyNav extends React.Component {

  setLabels (labels) {
    const [ label1, label2 ] = labels
    if (!label1 || !label2) return
    this.label1 = label1.textContent
    this.label2 = label2.textContent
  }

  getQuery (query, callback) {
    const el = document.querySelectorAll(query)
    if (!el) return
    if (callback) callback(el)
  }

  shouldComponentUpdate (nextProps, nextState) {
    if (this.state.fixed !== nextState.fixed) {
      this.getQuery('#navBar .form-group label', this.setLabels)
      return true
    }
    return false
  }

  render () {
    return (
      <div>
        <div className='form-group'>
          <label htmlFor='choice1'><h4>{this.label1}:</h4></label>
          <span id='choice1'> &nbsp;text</span>
        </div>
        <div className='form-group'>
          <label htmlFor='choice2'><h4>{this.label2}:</h4></label>
          <span id='choice2'> &nbsp;text</span>
        </div>
      </div>
    )
  }
}

export default StickyNav

You reference this here: 您参考this位置:

  setLabels (labels) {
    const [ label1, label2 ] = labels
    if (!label1 || !label2) return
    this.label1 = label1.textContent
    this.label2 = label2.textContent
  }

But this is not referencing the instance. 但是, this是不是引用实例。 You will have to bind that method in the constructor or use an ES7 class property for that: 您将必须在构造函数中绑定该方法,或为此使用ES7类属性:

  constructor(props) {
    super(props)
    this.setLabels = this.setLabels.bind(this)
  }

or 要么

  setLabels = () => {....}

You should be using react's state: 您应该使用react的状态:

constructor(props) {
    super(props)
    this.state = { 
        label1: null,
        label2: null,
    }
}

and then call setState({ label1: labels[0] }) for example. 然后例如调用setState({ label1: labels[0] })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM