【问题标题】:How to call 2 functions after the setState is called in React?在 React 中调用 setState 后如何调用 2 个函数?
【发布时间】:2019-11-27 09:50:17
【问题描述】:

我必须在 setState 更新后调用 2 个函数。 我想使用回调函数。 但问题是当前组件中存在一个函数,而我正在调用子组件的另一个函数(使用 refs)。 代码如下所示:

  handleChange_First = (event) => {
    

    const name = event.target.name;
   
    this.setState({
        [name]: event.target.value
    },() => {this.calculate()});
    this.child.handleChange(event)
   }

我想在setState 更改后立即致电this.calculate()this.child.handleChange(event)。 现在它正在更新当前组件(this.calculate)的值,但子组件(handleChange)的值没有更新。

或者如果有任何替代方法可以在 setState 之后同时调用这两个函数,那也会很有帮助。

【问题讨论】:

  • 是子组件的handleChange没有执行还是没有更新值?
  • 子组件正在执行,但从当前组件中获取先前的值而不是更新的值。(例如,您在当前组件中输入 1 它不会更改子组件中的任何内容,但是当您输入时2、子组件取1等)

标签: reactjs function callback


【解决方案1】:

在回调函数体中输入第二个函数调用。 试试这个:

handleChange_First = (event) => {
        const name = event.target.name;

        this.setState({[name]: event.target.value},() => {
                this.calculate();
                this.child.handleChange(event);
              });
}

【讨论】:

  • 我之前试过这个,但它会抛出错误:TypeError: Cannot read property 'target' of undefined。这个错误是因为 this.child.handleChange(event)。
【解决方案2】:

React 使用合成事件模式。来自docs

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

这也是同样的原因,你不能在回调中使用event。 (setState 是异步的,你必须首先使用回调的原因)

虽然有一个逃生舱,你可以通过调用 event.persist() 要求 React 不要合并事件

handleChange_First = (event) => {
  event.persist();
  const name = event.target.name;

  this.setState({[name]: event.target.value},() => {
     this.calculate();
     this.child.handleChange(event);
  });
}

【讨论】:

  • 你真是个救命恩人 :) 非常感谢。
【解决方案3】:

您可以尝试通过 setTimeout 调用,它会独立执行函数。

handleChange_First = (event) => {

    const name = event.target.name;

    this.setState({
        [name]: event.target.value
    },() => {this.calculate()});

    setTimeOut(()=>{
      this.child.handleChange(event);
    })
   }

【讨论】:

  • 它会抛出这个错误:TypeError: Cannot read property 'name' of null.
猜你喜欢
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2016-03-10
  • 2020-05-05
  • 1970-01-01
  • 2019-11-10
  • 2021-06-08
相关资源
最近更新 更多