我得到以下错误

无法读取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>
        );
    }
}

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

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

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

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

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


您需要将其绑定到构造函数,并记住对构造函数的更改需要重新启动服务器。否则,您将以相同的错误结束。


在ES7+ (ES2016)中,您可以使用实验函数绑定语法操作符::来绑定。这是一种语法糖,和Davin Tryon的答案一样。

然后你可以重写this.delta = this.delta.bind(this);到this.delta =::this.delta;


对于ES6+ (ES2015),您还可以使用ES6+箭头函数(=>)来使用此功能。

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

为什么?来自Mozilla文档:

在箭头函数之前,每个新函数都定义了自己的this值[…]。对于面向对象风格的编程来说,这被证明是令人讨厌的。 箭头函数捕获封闭上下文的this值[…]


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

用这个:

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

而不是:

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

ES5和ES6类之间有上下文差异。所以,实现之间也会有一点不同。

以下是ES5版本:

var Counter = React.createClass({
    getInitialState: function() { return { count : 1 }; },
    delta: function() {
        this.setState({
            count : this.state.count++
        });
    },
    render: function() {
        return (
            <div>
              <h1>{this.state.count}</h1>
              <button onClick={this.delta}>+</button>
            </div>
            );
    }
});

这是ES6版本:

class Counter extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count : 1 };
    }

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

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

注意,除了类实现中的语法差异之外,事件处理程序绑定也存在差异。

在ES5版本中,它是

              <button onClick={this.delta}>+</button>

在ES6版本中,它是:

              <button onClick={this.delta.bind(this)}>+</button>

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

/* 
 * 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() {
   //....
   }
}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>

    <script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
    <script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

  </head>
  <body>
  <div id="root"></div>
    <script type="text/babel">

        class App extends React.Component{

            constructor(props){
                super(props);
                this.state = {
                    counter : 0,
                    isToggle: false
                }
            this.onEventHandler = this.onEventHandler.bind(this);   
            }

            increment = ()=>{
                this.setState({counter:this.state.counter + 1});
            }

            decrement= ()=>{
                if(this.state.counter > 0 ){
                this.setState({counter:this.state.counter - 1});    
                }else{
                this.setState({counter:0});             
                }
            }
            // Either do it as onEventHandler = () => {} with binding with this  // object. 
            onEventHandler(){
                this.setState({isToggle:!this.state.isToggle})
                alert('Hello');
            }


            render(){
                return(
                    <div>
                        <button onClick={this.increment}> Increment </button>
                        <button onClick={this.decrement}> Decrement </button>
                        {this.state.counter}
                        <button onClick={this.onEventHandler}> {this.state.isToggle ? 'Hi':'Ajay'} </button>

                    </div>
                    )
            }
        }
        ReactDOM.render(
        <App/>,
        document.getElementById('root'),
      );
    </script>
  </body>
  </html>

你必须用'this'(默认对象)绑定你的方法。 不管你的函数是什么只要把它绑定到构造函数中。

constructor(props) {
    super(props);
    this.state = { checked:false };

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

handleChecked(){
    this.setState({
        checked: !(this.state.checked)
    })
}

render(){
    var msg;

    if(this.state.checked){
        msg = 'checked'
    }
    else{
        msg = 'not checked'
    }

    return (
        <div>               
            <input type='checkbox' defaultChecked = {this.state.checked} onChange = {this.handleChecked} />
            <h3>This is {msg}</h3>
        </div>
    );

你还可以使用:

<button onClick={()=>this.delta()}>+</button>

Or:

<button onClick={event=>this.delta(event)}>+</button>

如果你正在传递一些参数..


你不需要绑定任何东西,只需要像这样使用箭头函数:

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

        this.state = {
            count: 1
        };

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

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

你必须用这个关键字绑定新事件,正如我下面提到的…

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

        this.state = {
            count : 1
        };

        this.delta = 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>
        );
      }
    }

只需要更改bind语句 = > this.delta = this.delta.bind(this);


添加

onClick = {this.delta.bind ()}

就能解决问题。 当我们试图调用ES6类的函数时出现这个错误, 所以我们需要绑定这个方法。


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

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


检查状态 检查状态是否创建特定属性

这一点。状态= { 名称:", 电子邮件:”“ } this.setState(() => ({ Comments: Comments //注释状态不可用 }))

2.检查(这个) 如果你在任何函数(即handleChange)中执行setState,检查函数是否绑定到这个函数或函数应该是箭头函数。

## 3种方法绑定到下面的函数##

//3 ways for binding this to the below function handleNameChange(e) { this.setState(() => ({ name })) } // 1.Bind while callling function onChange={this.handleNameChange.bind(this)} //2.make it as arrow function handleNameChange((e)=> { this.setState(() => ({ name })) }) //3.Bind in constuctor constructor(props) { super(props) this.state = { name: "", email: "" } this.handleNameChange = this.handleNameChange.bind(this) }


箭头函数可以使您更容易避免绑定此关键字。像这样:

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

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

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

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 -箭头函数和词汇这


如果你使用的是ES5语法,那么你需要正确绑定它

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

如果你正在使用ES6及以上版本,你可以使用箭头函数,那么你不需要使用bind()它

delta = () => {
    // do something
  }

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

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


如果任何人在使用axios或任何fetch或get时寻找相同的解决方案,并使用setState将返回此错误。

你需要做的是在外部定义组件,如下所示:

componentDidMount(){
  let currentComponent = this;
  axios.post(url, Qs.stringify(data))
     .then(function (response) {
          let data = response.data;
          currentComponent.setState({
             notifications : data.notifications
      })
   })
}