React: “this” is undefined inside a component function

前端 未结 10 2119
春和景丽
春和景丽 2020-11-22 04:59
class PlayerControls extends React.Component {
  constructor(props) {
    super(props)

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


        
10条回答
  •  [愿得一人]
    2020-11-22 05:35

    If you call your created method in the lifecycle methods like componentDidMount... then you can only use the this.onToggleLoop = this.onToogleLoop.bind(this) and the fat arrow function onToggleLoop = (event) => {...}.

    The normal approach of the declaration of a function in the constructor wont work because the lifecycle methods are called earlier.

提交回复
热议问题