【问题标题】:`event` object is unaccessible within this.setState() - React.js [duplicate]在 this.setState() 中无法访问“事件”对象-React.js [重复]
【发布时间】:2018-10-03 09:13:24
【问题描述】:

无法访问 this.setState 中的 event 对象,因为我试图访问 this.setState 中的事件一回调。它会以Uncaught TypeError: Cannot read property 'value' of null 的形式抛出错误,有什么建议可以访问它吗?

注意:getReportType 在下拉菜单中的值被选中时被调用

以下是Class部分

getReportType(event) {
      console.log(event.target.value) //MetricsByContent
      this.setState(prevState => ({
        metricsParams: {
            ...prevState.metricsParams,
            reportType: event.target.value
        }
      }))
    }

以下是render()部分

render() {
      return (
          <div
              <select id="metricsDropDown" className="browser-default" onChange={this.getReportType}>
                <option value="MetricsByContent">Metrics By Content</option>
                <option value="MetricsByUser">Metrics By User</option>
              </select>
        </div>
      )
    }

【问题讨论】:

  • “无法访问事件对象” -> 这甚至意味着什么?您得到的确切错误是什么?
  • 这个函数是怎么调用的?如果在函数内添加console.log(event)event 定义是否正确?
  • @RamyaRamanathan:当然不是这里的问题。 eventthis 没有连接
  • 最好的办法是创建console.log(event) 并查看其中包含哪些数据
  • 由于SyntheticEvent,解决方案是将值存储在变量中或使用event. persist()

标签: javascript reactjs


【解决方案1】:

事件对象被 React 清除,如果你想在 setState 回调中使用它,你要么使用event.persist(),要么将值复制到另一个变量中

根据React docs

SyntheticEvent 是池化的。这意味着SyntheticEvent 对象将被重用,并且所有属性都将在 事件回调已被调用。这是出于性能原因。作为 因此,您不能以异步方式访问事件。

getReportType(event) {
      event.persist();
      this.setState(prevState => ({
        metricsParams: {
            ...prevState.metricsParams,
            reportType: event.target.value
        }
      }))
    }

getReportType(event) {
      const value = event.target.value;
      this.setState(prevState => ({
        metricsParams: {
            ...prevState.metricsParams,
            reportType: value
        }
      }))
    }

【讨论】:

  • @DanielHilgarth,我做到了
猜你喜欢
  • 2020-09-18
  • 1970-01-01
  • 2020-06-14
  • 2020-02-28
  • 2017-09-04
  • 1970-01-01
  • 2019-10-06
  • 2012-10-15
  • 2011-11-05
相关资源
最近更新 更多