【问题标题】:ReactJS: Showing Modals and RerenderingReactJS:显示模态和重新渲染
【发布时间】:2017-08-30 07:28:05
【问题描述】:

所以,我正在尝试找出最好的方法:

在反应中显示模态或隐藏模态。在我的主页上,我有很多照片,我当前的状态设置是:

export default class Main extends TrackerReact(Component) {
  constructor(props) {
   super(props);
   this.state = {
     showModal: false,
     modalPhoto: {},
   };

   this.close = this.close.bind(this);
   this.open = this.open.bind(this);
}
close() { this.setState({ showModal: false }); } // basic modal close
open(e) {
  this.setState({ modalPhoto: e });
  this.setState({ showModal: true });
}

当我将 showModal 设置为 true 时,它​​会传递给 bootstrap-react 模态:

<Modal
  show={this.props.show} >
  // ...loads modalPhoto form main state.modalPhoto
</Modal>

问题:每次打开模态框时,它都会改变主状态并重新渲染主页面。阻止这种重新渲染发生的最佳实践方法是什么?我试过了:

// in the main component
shouldComponentUpdate(nextProps, nextState) {
  if (this.state.showModal !== nextState.showModal) {
    return false;
  } else {
    return true;
  } // PS. I know this is wrong, but I was desperate...

我也在考虑使用 jquery 绕过外部并手动显示模态或隐藏模态,因此不改变状态。这样做的问题很明显,Unmount 和 ReceiveProps 很难维护。

我也知道 TrackerReact 包会在数据更改时重新渲染,但在打开和关闭模式时不会更改任何数据。

想法?

【问题讨论】:

  • 这就是 react 的工作原理。导致顶级渲染调用是否存在问题?
  • 模态是否需要在基类中?它可以是子组件吗?在当前设置下,您的模式只能显示是否发生渲染,这将是其他所有内容的渲染。
  • 只是作为一种快速优化。将您的 open 函数更改为仅调用 setState 一次 this.setState({ showModal: true, modalPhoto: e }); 其性能提高一倍!两个 setstate 调用将执行两个生命周期(包括渲染)。但是你可以把它变成一个 setState :)
  • 实际上,两次setState 调用不会导致两次重新渲染。它们将被合并并作为一个应用。 "setState() does not immediately mutate this.state but creates a pending state transition"
  • @btidwell 不错!很高兴知道。最好将两者合并在一起以获得更简洁的代码:)

标签: reactjs ecmascript-6


【解决方案1】:

也许您应该考虑使用组件来包装您的模态并管理状态。您的主要组件将不再更新。

正如上面的 cmets 所说,一旦状态更新就刷新视图是 React 的工作方式

Dan Abramov 在 Stack Overflow 上写了一个非常有趣的答案,关于如何处理带有 redux 状态的 Modals:How can I display a modal dialog in Redux that performs asynchronous actions?

尝试从这篇文章中获得一些灵感。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2022-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2016-09-09
    • 2020-06-20
    • 2019-11-30
    • 2014-09-30
    相关资源
    最近更新 更多