javascript - 无法读取未定义 ReactJS 的属性 'setState'

标签 javascript reactjs

我试图在函数内的 React 中设置状态,但是收到一条错误消息:无法读取未定义的属性“setState”。

下面是我的代码,我在构造函数中调用状态,然后在 addTimes 函数中设置状态并将其绑定(bind)到该函数,但是我仍然收到错误。

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

  }
  render(){
    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);
        });
      } else if(times.includes(id)){
        times.remove(id)
      }
      console.log(times);
      addTimes = () => {
        this.setState({
          times: times
        });
      }
    }

最佳答案

您尚未将该函数绑定(bind)到该类。尝试做

addTimes = (id) => {
  // code here
}

在组件类中

关于javascript - 无法读取未定义 ReactJS 的属性 'setState',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51241187/

相关文章:

javascript - Ember 操作阻止设置复选框值

javascript - Bootstrap 开关 setState 给出 js 错误

javascript - React Native - Alert.alert 似乎没有调用函数

javascript - 与 webpack 一起安装时未定义 React

javascript - 重新渲染和状态设置时状态对象是否保持相同的实例?

php - 如何将服务器数据传递给 React 组件

javascript - Gulp Bundle + Browserify 处理多个文件

reactjs - React prop 验证日期对象

javascript - 在 HTML、CSS、JQuery 中用其他小形状填充形状

javascript - 如何检测源/调试 Lexer 的空值