为什么React setState回调函数有时无法触发?

时间:2019-07-26 01:01:11

标签: javascript reactjs

我有一个SVG按钮,其中包含子元素(多边形)。 handleMouseLeave函数用于设置状态,然后利用其回调立即更新子级。即使'mouseleave'和'callback'均按顺序记录日志,但回调区域内的其余代码也不会始终触发。

是否有更好或正确的方法来处理回调?

  handleMouseLeave = (e) => {
    console.log('mouseleave')
    const polygons = [...e.target.children];
    this.setState({
      translate: "translateX(-100%)",
      opacity: 0
    }, () => {
      console.log('callback')
      polygons.forEach(child => {
        child.style.transform = this.state.translate;
        child.style.opacity = this.state.opacity;
      });
    });
  };

-

render() {
    return(
      <button>
        <HeroButtonSVG
          id="HeroButton"
          onMouseEnter={this.handleMouseEnter}
          onMouseLeave={this.handleMouseLeave}
        />
        <span>Check out my work<i className="fas fa-chevron-right"></i></span>
      </button>
    );
  };

2 个答案:

答案 0 :(得分:0)

这似乎是一个事件绑定问题,因为默认情况下未绑定类方法。

要解决此问题,您可以将以下内容添加到render函数,该函数将通过使用箭头函数自动绑定来绑定事件:

<HeroButtonSVG
   id="HeroButton"
   onMouseEnter={e => this.handleMouseEnter(e)}
   onMouseLeave={e => this.handleMouseLeave(e)}
/>

答案 1 :(得分:0)

事实证明,实际问题源自子SVG上的指针事件。该问题与React的setState回调函数无关。

我在这里跟踪了问题:https://github.com/facebook/react/issues/4492