React.js中显示了模态时如何执行某些操作

How to do something when modal is shown in React.js?

本文关键字:执行 操作 何执行 js 显示 模态 React      更新时间:2023-09-26

我使用的是react.jsreduxredux-modal。我想在显示我的模态时执行一段代码。

当我把代码放在componentWillMount中时,它只是在第一时间执行。

  componentWillMount() {
    // Just execute one time
    // Do something
  }

redux-modal使用show状态变量来显示或隐藏模态,因此我使用以下代码来处理显示事件:

  componentWillReceiveProps(nextProps) {
    // When modal is shown
    if (!this.props.show && nextProps.show) {
       // Do something
    }
  }

除了第一次安装modal外,它运行良好。

现在我将使用componentWillMountcomponentWillReceiveProps来处理模态显示事件。

有没有更好的解决方案来处理模态表演事件

您可以简单地将代码放入渲染函数中,如下所示:

render() {
  {(this.props.show) ? <MyModalComponent/> : null}
  ... // other components to render
}

如果您使用componentDidMount()激发API调用,那么使用上面的代码,您的流将是:

  • 第一次渲染:this.props.show == false
  • 运行render()时,组件将在没有模态的情况下进行渲染
  • componentDidMount()正在运行,它将触发API调用
  • API调用的结果更新存储,将show设置为true
  • 存储更新触发新的渲染周期
  • 下一个渲染周期:this.props.show == true
  • render()运行时,组件将以模态呈现
  • componentDidMount()未运行,因为这是第二次渲染)