Uncaught TypeError: Cannot read properties of undefined (reading ‘setState’)

话不多说,代码如下:

import React, { Component } from 'react'

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = { route: "hello" }
  }
  
  change() {
    this.setState({ route: "home" })
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <button onClick={this.change}>按钮</button>
          {this.state.route}
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
        </header>
      </div>
    )
  }
}

在点击按钮时报了这个错,意思是change方法里的this访问不到这个setState()方法

经过查阅资料,发现这种常规的定义函数方法,在函数调用时,没有用call、apply指定this的指向时,默认的this是undefined,所以调用不到setState

出现这样的问题,我的解决方法使用箭头函数,箭头函数里的this默认是与外层函数保持一致的
所以上述方法只需改成:

  change=()=> {
    this.setState({ route: "home" })
  }

就可以完美执行了。

网上找的一些方法都是改绑change中this的指向,感觉比用箭头函数要麻烦。

谢谢观看

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐