this.state of undefined虽然默认状态设置为null或''

时间:2017-12-15 14:18:42

标签: reactjs ecmascript-6

当状态在构造函数中声明了默认状态时,为什么我仍然得到this.state的未定义错误?

constructor() {
    super()
    this.state = {
      data: data,
      q: null
    }
  }

  filterC(o) {
    if (this.state.q) { //wtf??
      return o['Id'].includes(this.state.q)
    }
    return o
  }

演示:https://codesandbox.io/s/v35r8vyqwl

1 个答案:

答案 0 :(得分:0)

您需要将此绑定到函数:

constructor(props) {
    super(props)
    this.state = {
      data: data,
      q: null
    }

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

  filterC(o) {
    if (this.state.q) {
      return o['Id'].includes(this.state.q)
    }
    return o
  }