前端

React中input双向绑定问题

2019-08-03聚力创意

在使用 React 开发搜索功能的时候,遇到了e.target值为null的问题和操作event处于异步操作中

setKeyword = e => {
  this.setState(() => ({
    keyword: e.target.value
  }))
}

<input type="text" value={this.state.keyword} onChange={this.setKeyword} />
// Uncaught TypeError: Cannot read property 'value' of null
// This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property `target` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().

事件属性会在事件调用后被回收,节省内存开销,即不能异步访问,因为setState是异步操作,所以访问不到e.target,当然也可以e.persist()来设置不回收,但不推荐,会影响性能。

只要不在setState的更新函数中访问event事件对象就可以解决

setKeyword = e => {
  const keyword = e.target.value
  this.setState(() => ({
    keyword: e.target.value
  }))
}
蜀ICP备17044229号