反应:“ this”在组件函数中未定义

JavaScript

SamItachi

2020-03-11

class PlayerControls extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      loopActive: false,
      shuffleActive: false,
    }
  }

  render() {
    var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"

    return (
      <div className="player-controls">
        <FontAwesome
          className="player-control-icon"
          name='refresh'
          onClick={this.onToggleLoop}
          spin={this.state.loopActive}
        />
        <FontAwesome
          className={shuffleClassName}
          name='random'
          onClick={this.onToggleShuffle}
        />
      </div>
    );
  }

  onToggleLoop(event) {
    // "this is undefined??" <--- here
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
  }

我想loopActive在切换时更新状态,但this在处理程序中未定义对象。根据教程文档,我this应该引用该组件。我想念什么吗?

第744篇《反应:“ this”在组件函数中未定义》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
村村小小十三 2020.03.11

就我而言,这是解决方案=()=> {}

methodName = (params) => {
//your code here with this.something
}
HarryL梅 2020.03.11

如果在生命周期方法(例如componentDidMount ...)中调用创建的方法,则只能使用this.onToggleLoop = this.onToogleLoop.bind(this)和箭头功能onToggleLoop = (event) => {...}

在构造函数中声明函数的常规方法将不起作用,因为生命周期方法被更早地调用了。

Stafan逆天 2020.03.11

这样编写函数:

onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}

胖箭头功能

关键字的绑定,外部和内部的胖箭头功能相同。这与用function声明的函数不同,后者可以在调用时将其绑定到另一个对象。维护this绑定对于诸如映射这样的操作非常方便:this.items.map(x => this.doSomethingWith(x))。

Admin 2020.03.11

您应该注意到,这this取决于调用函数的方式,即:当函数作为this对象的方法被调用时,其功能被设置为调用该方法的对象。

this可在JSX上下文中作为组件对象访问,因此可以将所需的方法作为this方法内联调用

如果您只是传递对函数/方法的引用,似乎react会将其作为独立函数调用。

onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined

onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
泡芙Pro 2020.03.11

我在render函数中遇到了类似的绑定,最终this以以下方式传递的上下文

{someList.map(function(listItem) {
  // your code
}, this)}

我也用过:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}
理查德猿JinJin 2020.03.11

有两种方法。

一种是添加 this.onToggleLoop = this.onToggleLoop.bind(this);构造函数。

另一个是箭头功能 onToggleLoop = (event) => {...}

然后是onClick={this.onToggleLoop.bind(this)}

小哥达蒙 2020.03.11

ES6 React.Component不会自动将方法绑定到自身。您需要将它们自己绑定到构造函数中。像这样:

constructor (props){
  super(props);

  this.state = {
      loopActive: false,
      shuffleActive: false,
    };

  this.onToggleLoop = this.onToggleLoop.bind(this);

}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android