【发布时间】:2021-12-09 00:03:44
【问题描述】:
我一直在阅读这些链接:
https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate
https://reactjs.org/blog/2018/10/23/react-v-16-6.html
在第一个链接中它说(https://reactjs.org/docs/hooks-faq.html#from-classes-to-hooks):
shouldComponentUpdate:参见 React.memo
第二个链接还指出:
当使用 PureComponent 或 shouldComponentUpdate 的输入属性相同时,类组件可以退出渲染。现在你可以通过将函数组件包装在 React.memo 中来对它们做同样的事情。
想要什么:
我希望 Modal 仅在 Modal 可见时渲染(由 this.props.show 管理)
对于类组件:
shouldComponentUpdate(nextProps, nextState) {
return nextProps.show !== this.props.show;
}
如何在功能组件中使用 memo 代替 - 在 Modal.jsx 中?
相关代码:
功能组件Modal.jsx(不知道怎么查看props.show)
import React, { useEffect } from 'react';
import styles from './Modal.module.css';
import BackDrop from '../BackDrop/BackDrop';
const Modal = React.memo(props => {
useEffect(() => console.log('it did update'));
return (
<React.Fragment>
<BackDrop show={props.show} clicked={props.modalClosed} />
<div
className={styles.Modal}
style={{
transform: props.show ? 'translateY(0)' : 'translateY(-100vh)',
opacity: props.show ? '1' : '0'
}}>
{props.children}
</div>
</React.Fragment>
);
});
export default Modal;
类组件 PizzaMaker jsx 中渲染 Modal 的部分:
return (
<React.Fragment>
<Modal show={this.state.purchasing} modalClosed={this.purchaseCancel}>
<OrderSummary
ingredients={this.state.ingredients}
purchaseCancelled={this.purchaseCancel}
purchaseContinued={this.purchaseContinue}
price={this.state.totalPrice}
/>
</Modal>
...
</React.Fragment>
);
【问题讨论】:
-
与
React.memo,组件只会在props改变时重新渲染,所以这基本上是你想要的 -
我只希望它在
props.show为真时重新渲染,而不是props本身。因为只要它是隐形的,就可以提高它的性能。通过单击“立即订购”按钮可以看到它,该按钮触发 props.show 为真并显示位于 Modal 中的订单摘要可见。
标签: javascript reactjs functional-programming react-hooks