【问题标题】:TypeError: _this2 is undefined REACTJSTypeError: _this2 is undefined REACTJS
【发布时间】:2019-11-26 19:42:34
【问题描述】:

为了快速解释我的问题,在我的渲染中,我调用了一个函数,该函数通过 map 函数显示我的数组的每个元素。 当我单击按钮时,我想将元素发送到另一个函数。但是当我点击按钮时出现以下错误:“TypeError: _this2 is undefined”,这是我的代码的一些截图:

提前谢谢你!

【问题讨论】:

  • 您对地图应用的功能正在创建一个无法访问的新 this 上下文。我敢打赌,如果您将其更改为箭头函数或将其绑定到当前的 this 上下文,它将解决问题。

标签: javascript reactjs scope


【解决方案1】:

默认情况下,JavaScript 中的函数调用会创建自己的 this 上下文。如果您将传统函数应用于映射,它会在调用该函数时为每次迭代创建一个唯一的 this 上下文。为了防止这种情况发生,您可以显式地告诉函数 this 上下文要绑定到该函数,或者您可以使用箭头函数,它会自动将当前的 this 上下文应用于创建的上下文。

我在下面创建了一个示例来说明问题。在 List 组件中,可以看到有一个 renderList 函数调用一个 map 迭代渲染列表中的项目。下面的代码不起作用,因为 map 函数创建了一个未定义 renderItem 函数的上下文:

class List extends Component {
  constructor(props) {
    super(props);
  }

  renderList(list) {
    return (
      <div>
        {
          list.map(function(item) {
            return <div>{this.renderItem(item)}</div>
          })
        }
      </div>
    )
  }

  renderItem(item) {
    return <div style={{color: 'green'}}>{item}</div>
  }

  render() {
    return <div>
      {
        this.renderList(['one', 'two', 'three'])
      }
    </div>
  }
}

要解决此问题,请将其绑定到当前上下文:

renderList(list) {
  return (
    <div>
      {
        list.map(function(item) {
          return <div>{this.renderItem(item)}</div>
        }.bind(this))
      }
    </div>
  )
}

OR 隐式绑定当前 this 上下文箭头函数:

renderList(list) {
  return (
    <div>
      {
        list.map(item => {
          return <div>{this.renderItem(item)}</div>
        })
      }
    </div>
  )
}

【讨论】:

  • 第一个解决方案在我的情况下不起作用(错误是未定义)。但是您提出的第二种解决方案非常有效,谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-02-09
  • 2017-09-08
  • 1970-01-01
  • 2020-07-01
  • 2021-11-24
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多