我正在学习 React 并正在开发一个简单的小应用程序。该应用程序包含一行,其中有选项卡和下拉菜单。从该下拉列表中,您可以打开用于添加/删除/编辑所述选项卡的模式。
我注意到,当应用程序启动时以及每次单击任何选项卡(甚至当前选定的选项卡)时,所有模态都会调用其渲染方法。我对 React 很陌生,所以我很困惑这是否应该发生。不过,该应用程序似乎按预期工作。
下面是代码的 super 简化版本,仅包含必要的部分:
app.js
class App extends React.Component {
// ...
// state is { modals: { addTab: false, editTab: false, removeTab: false } }
closeModal = (modalState) => {
const obj = this.state.modals;
obj[modalState] = false;
this.setState(obj);
}
render() {
<div className="App container-fluid">
// ...
<AddTabModal showModal={this.state.modals.addTab} closeModal={this.closeModal} ... />
// ...
</div>
}
}
AddTabModal.js
class AddTabModal extends React.Component {
// ...
render() {
// This gets triggered every time I click any tab or the dropdown menu.
// Even if the modal is not visible.
console.log('Render add tab modal');
return (
<Modal show={this.props.showModal} ... >
// ...
<Modal.Footer>
<Button onClick={() => { this.props.closeModal('addTab'); }}>Close</Button>
</Modal.Footer>
</Modal>
);
}
}
我还读到,在 JSX 中使用箭头函数是一种不好的模式,但如果我将按钮更改为:
<Button onClick={this.props.closeModal('addTab')}>Close</Button>
它应该仍然只在我单击按钮时运行,对吧?但该应用程序从一开始就完全锁定,并且出现“超出最大更新深度”错误。我相信这与上述问题有关,因为我的应用程序中没有任何 componentWillUpdate/componentDidUpdate 方法。
最佳答案
您可以采取以下几项措施来优化:
- 确保传递到模式中的所有 props 都是不可变的
- 将 close 函数提取到类方法中
- 使用
PureComponent
来阻止渲染,除非 props 发生变化
class AddTabModal extends PureComponent {
// ...
onCloseModal = () => {
this.props.closeModal('addTab');
}
render() {
// This gets triggered every time I click any tab or the dropdown menu.
// Even if the modal is not visible.
console.log('Render add tab modal');
return (
<Modal show={this.props.showModal} ... >
// ...
<Modal.Footer>
<Button onClick={this.onCloseModal}>Close</Button>
</Modal.Footer>
</Modal>
);
}
}
<小时/>
I also read that using arrow functions inside JSX is a bad pattern, but if I change the button to:
<Button onClick={this.props.closeModal('addTab')}>Close</Button>
这是因为 () => this.props.closeModal('addTab')
创建了一个新函数,调用该函数时将关闭模式。但如果您只有 this.props.closeModal('addTab')
,关闭模态函数会立即被调用。
避免额外的匿名函数的方法是将其提取到类方法中,如上面的代码所示。
关于javascript - 使用 React 和 React-bootstrap 应用程序进行不必要的模态渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46723942/