我得到以下错误

无法读取undefined的属性“setState”

即使在构造函数中绑定了delta。

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}

当前回答

这个问题有两种解决方案:

第一个解决方案是给你的组件添加一个构造函数,并像下面这样绑定你的函数:

constructor(props) {
        super(props);

        ...

        this.delta = this.delta.bind(this);
    }

所以这样做:

this.delta = this.delta.bind(this); 

而不是这样:

this.delta.bind(this);

第二个解决方案是使用箭头函数:

delta = () => {
       this.setState({
           count : this.state.count++
      });
   }

实际上箭头函数并不绑定它自己的这个。箭头函数在词法上绑定它们的上下文,因此这实际上引用了原始上下文。

有关bind函数的更多信息:

绑定函数 理解JavaScript Bind ()

有关箭头函数的更多信息:

Javascript ES6 -箭头函数和词汇这

其他回答

如果使用内部axios,则在then中使用箭头(=>)

Axios.get ('abc.com').then((response) => {});

这个错误可以通过各种方法来解决

如果你使用的是ES5语法,那么根据React js文档你可以使用 必须使用绑定方法。 上面的例子是这样的: this.delta = this。delta。bind(this) 如果你使用的是ES6语法,那么你不需要使用bind方法,你可以 可以这样做: δ= ()= > { this.setState ({ Count: this.state.count++ }); }

虽然这个问题已经有了答案,但我还是想分享一下我的答案,希望对大家有所帮助:

/* 
 * The root cause is method doesn't in the App's context 
 * so that it can't access other attributes of "this".
 * Below are few ways to define App's method property
 */
class App extends React.Component {
  constructor() {
     this.sayHi = 'hello';
     // create method inside constructor, context = this
     this.method = ()=> {  console.log(this.sayHi) };

     // bind method1 in constructor into context 'this'
     this.method1 = this.method.bind(this)
  }

  // method1 was defined here
  method1() {
      console.log(this.sayHi);
  }

  // create method property by arrow function. I recommend this.
  method2 = () => {
      console.log(this.sayHi);
  }
   render() {
   //....
   }
}

这是因为这个没有和这个绑定。

为了绑定,在构造函数中设置this.delta = this.delta.bind(this):

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

    this.delta = this.delta.bind(this);
}

目前,您正在调用bind。但是bind返回一个绑定函数。您需要将函数设置为其绑定值。

当在React中使用ES6代码时,总是使用箭头函数,因为这个上下文会自动与它绑定

用这个:

(videos) => {
    this.setState({ videos: videos });
    console.log(this.state.videos);
};

而不是:

function(videos) {
    this.setState({ videos: videos });
    console.log(this.state.videos);
};