簡體   English   中英

無法讀取undefined,React.js的屬性'bind'

[英]Cannot read property 'bind' of undefined, React.js

當它綁定到我的addTimes函數時,我得到一個錯誤說明:無法讀取undefined的屬性'bind'。

我在ReactjJS和Webpack中構建。 我最近有另一個問題,人們建議:

this.addTimes = this.addTimes.bind(this);

請參閱: 無法讀取未定義的ReactJS的屬性“setState”

class Settings extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      times: []
    };

  }
  render(){
    this.addTimes = this.addTimes.bind(this);
    Array.prototype.remove = function() {
        var what, a = arguments, L = a.length, ax;
        while (L && this.length) {
            what = a[--L];
            while ((ax = this.indexOf(what)) !== -1) {
                this.splice(ax, 1);
            }
        }
        return this;
    };

    var currentTicked = [];
    var times =[]
    function addTimes(id){
      var index = times.indexOf(id);
      if (!times.includes(id)) {
        $("input:checkbox[name=time]:checked").each(function(){
          currentTicked.push($(this).val());
          times = times.concat(currentTicked)
          times = jQuery.unique(times);
          currentTicked = [];

        });
      } else if(times.includes(id)){
        times = times.remove(id);
      }
      console.log(times);
      this.setState = {
        thims: times
      }
    }

為了能夠綁定addTimesthis在構造函數中, addTimes必須在你的類中的方法,不只是在渲染方法的功能。

class Settings extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      times: []
    };
    this.addTimes = this.addTimes.bind(this);
  }

  addTimes(id) {
    // ...
  }
}

如果你想創建addTimes的渲染方法,你可以只綁定this到功能有:

function addTimes(id) {
 // ...
}.bind(this);

或者你可以把它改成箭頭功能:

const addTimes = (id) => {
  // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM