javascript - 当 React.js 中显示模态时如何处理?

标签 javascript reactjs redux

我正在使用 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
    }
  }

除了第一次安装模态之外,它运行良好。

现在我使用 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() 未运行,因为这是第二次渲染)

关于javascript - 当 React.js 中显示模态时如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019312/

相关文章:

javascript - 使用 Meetups API javascript 获取数据

javascript - VueJS splice 删除数组中的所有项目

reactjs - react 引用 : what is equal to document. querySelectorAll

reactjs - 如何测试渲染的 React 组件的 HTML?

reactjs - 前端和仪表板的 React Redux 文件夹结构

ReactJS、SocketIO 和 Redux - 什么是正确的设计

javascript - 为什么 Bootstrap typeahead 不适用于具有相同 ID 的输入元素?

javascript - 带有参数的 ui-sref 嵌套状态

reactjs - React 数组状态不推送值

angular - NgRx 通过 dispatch 方法传递 payload 来更新 store