【发布时间】: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