【问题标题】:ReactJS. - Why does this work in ReactJS and not the other way反应JS。 - 为什么这在 ReactJS 中有效,而不是其他方式
【发布时间】:2020-08-10 21:01:37
【问题描述】:

您好,我想了解为什么此特定代码有效而我之前的代码无效。

我已经提供了下面两个sn-ps:

工作代码:

handleInputChange = (e) => {
      let { value } = e.target;
      this.setState(state => { return ({searchField : value}) }, () => console.log("new state is ", this.state.searchField))
  }

不工作的代码: 我在这里得到的错误是cannot read property value of null.

handleInputChange = (e) => {
      this.setState(state => { return ({searchField : e.target.value}) }, () => console.log("new state is ", this.state.searchField))
  }

这是两者都通用的渲染方法:

  render() {
    let { monsters, searchField } = this.state;

    const filteredMonsters = monsters.filter((monster) => {
        return monster.name.toLowerCase().includes(searchField.toLowerCase());
    })

    return (
        <div className="App">
            <input type="search" placeholder="Monster Name" onChange={this.handleInputChange}/>
          <CardList monsters={filteredMonsters}/>
        </div>
    );

有人能解释一下为什么解构语法有效吗?

谢谢!

【问题讨论】:

  • 您正在传递一个函数,该函数将在未来某个时间访问e.target,而工作的 sn-p 在事件发生时提取值。显然,除非立即访问,否则不能保证该事件提供.target
  • 谢谢,您能否解释一下为什么 this.setState({searchField : e.target.value}) 有效,即使 this.setState 是异步的,这仍然有效。
  • 它是异步的,但您传递的是一个值,即e.target.value 的当前值。在你的非工作代码中,你传递了一个 function,只有当它实际运行时,React 才会尝试访问该值,但此时 e 指向的对象已经被清除。基本演示:jsfiddle.net/khrismuc/qs316vkg

标签: javascript reactjs react-redux


【解决方案1】:

事件是传递给事件处理程序的合成事件。来自docs

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

function onClick(event) {
  console.log(event); // => nullified object.
  console.log(event.type); // => "click"
  const eventType = event.type; // => "click"

  setTimeout(function() {
    console.log(event.type); // => null
    console.log(eventType); // => "click"
  }, 0);

  // Won't work. this.state.clickEvent will only contain null values.
  this.setState({clickEvent: event});

  // You can still export event properties.
  this.setState({eventType: event.type});
}

注意

如果你想以异步方式访问事件属性,你 应该在事件上调用event.persist(),这将删除 池中的合成事件,并允许对该事件的引用 由用户代码保留。

【讨论】:

  • 感谢您的出色回答,您能否解释一下为什么这个工作 this.setState({searchField : e.target.value}) 即使 this.setState 是异步的,这仍然有效。
  • @pi2018 大多数情况下,如果在setState内部使用回调,则事件不会持续
【解决方案2】:

因为一,setState 是异步的,二,React 重用了合成事件对象。因此,当 setState 的回调被执行e 的值不必(并且显然不是)与 setState 本身被调用时相同。

const value = e.target.value; this.setState( // use the value primitive here 应该也能正常工作。

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 2015-03-08
    • 1970-01-01
    • 2010-11-23
    • 2020-05-04
    • 1970-01-01
    • 2011-09-20
    • 2015-09-12
    • 2021-05-21
    相关资源
    最近更新 更多