useState方法不允许访问外部变量?

时间:2020-01-17 01:59:53

标签: javascript reactjs

奇怪为什么以下方法不起作用:

  const onChange = e => {
    console.log(e.target.value)
    setEmails(prevEmails => ({
      ...prevEmails,
      reports: e.target.value
    }))
  }

事件'e'变量console.logs,但是在setEmails中使用时,它说找不到null值? 确切的错误:

Cannot read property 'value' of null

我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

您应该将值保存到另一个变量,或使用e.persist()

const onChange = e => {
    console.log(e.target.value);
    let myValue = e.target.value;
    setEmails(prevEmails => ({
        ...prevEmails,
        reports: myValue
    }))
}

这是因为出于性能原因,在React中使用synthetic events。在文档的 event pooling 部分中:

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