响应-未捕获的类型错误:无法读取未定义的属性'setState'。

[英]React - uncaught TypeError: Cannot read property 'setState' of undefined


I am getting the following error

我得到了下面的错误

Uncaught TypeError: Cannot read property 'setState' of undefined

未捕获的TypeError:无法读取未定义的属性'setState'

even after binding delta in the constructor.

甚至在构造函数中绑定了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>
        );
    }
}

10 个解决方案

#1


229  

This is due to this.delta not being bound to this.

这是由于。

In order to bind set this.delta = this.delta.bind(this) in the constructor:

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

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

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

Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value.

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

#2


75  

In ES7+ (ES2016) you can use the experimental function bind syntax operator :: to bind. It is a syntactic sugar and will do the same as Davin Tryon's answer.

在ES7+ (ES2016)中,可以使用实验函数bind语法操作符::to bind。这是一种句法糖,和戴维·特里翁的答案一样。

You can then rewrite this.delta = this.delta.bind(this); to this.delta = ::this.delta;

然后可以重写this.delta = this.delta.bind(这个);this.delta =:this.delta;


For ES6+ (ES2015) you can also use the ES6+ arrow function (=>) to be able to use this.

对于ES6+ (ES2015),您还可以使用ES6+ arrow函数(=>)来使用它。

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

Why ? From the Mozilla doc :

为什么?Mozilla文档:

Until arrow functions, every new function defined its own this value [...]. This proved to be annoying with an object-oriented style of programming.

在箭头函数之前,每个新函数都定义自己的这个值[…]。事实证明,这种面向对象的编程风格很烦人。

Arrow functions capture the this value of the enclosing context [...]

箭头函数捕获包围上下文的这个值[…]

#3


24  

There is a difference of context between ES5 and ES6 class. So, there will be a little difference between the implementations as well.

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

Here is the ES5 version:

以下是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>
            );
    }
});

and here is the ES6 version:

这是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>
            );
    }
}

Just be careful, beside the syntax difference in the class implementation, there is a difference in the event handler binding.

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

In the ES5 version, it's

在ES5版本中,它是

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

In the ES6 version, it's:

在ES6版本中,它是:

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

#4


12  

When using ES6 code in React always use arrow functions, because the this context is automatically binded with it

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

Use this:

用这个:

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

instead of:

而不是:

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

#5


4  

You have to bind your methods with 'this' (default object). So whatever your function may be just bind that in the constructor.

你必须用“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>
    );

#6


3  

You need to bind this to the constructor and remember that changes to constructor needs restarting the server. Or else, you will end with the same error.

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

#7


1  

You can also use:

您还可以使用:

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

Or:

或者:

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

If you are passing some params..

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

#8


0  

though this question had a solution already, I just want to share mine to make it be cleared, hope it could help:

虽然这个问题已经有了解决的办法,我只是想分享一下我的解决办法,希望能有所帮助:

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

#9


0  

<!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>

#10


0  

You dont have to bind anything, Just use Arrow functions like this:

你不需要绑定任何东西,只需使用如下的箭头函数:

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>
    );
}

}

}


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/08/31/49cd6880d668976624bc380eb116ccae.html



 
  © 2014-2022 ITdaan.com 联系我们: