为什么解构对事件起作用,而没有它就不起作用

Why does destructoring works with events, and wont work without it

当我使用这段代码时:

 onChange = e => {
  const { name, value } = e.target;
     this.setState(currentState => ({
      tempInput: { ...currentState.tempInput, [name]: value }
    }));
  };

一切正常,但当我这样做时:

 onChange = e => {
     this.setState(currentState => ({
      tempInput: { ...currentState.tempInput, [e.target.name]: e.target.value }
    }));
  };

我收到一个错误:类型错误:e.target 为空, 有什么不同?我错过了什么吗?

因为this.setState()asynchronous。因此 e 在执行时变为未定义。

为了缓解它,您可以在 onChange 函数参数中析构 e,这会在 onChange 函数范围内保留 namevalue 定义:

 onChange = ({ target: { value, name } }) => {
     this.setState(currentState => ({
      tempInput: { ...currentState.tempInput, [name]: value }
    }));
  };

或者...您可以在执行 this.setState() 之前析构 e.target,这也使 namevalue 定义在 onChange 功能范围内:

 onChange = e => {
     const { name, value } = e.target;
     this.setState(currentState => ({
      tempInput: { ...currentState.tempInput, [name]: value }
    }));
  };