Mat*_*san 4 javascript functional-programming reactjs react-hooks
我一直在阅读以下链接:
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;
}
Run Code Online (Sandbox Code Playgroud)
我该如何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;
Run Code Online (Sandbox Code Playgroud)
类组件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>
);
Run Code Online (Sandbox Code Playgroud)
Oli*_*ssé 14
这是React.memo的文档
您可以通过一个函数来控制比较:
const Modal = React.memo(
props => {...},
(prevProps, nextProps) => prevProps.show === nextProps.show
);
Run Code Online (Sandbox Code Playgroud)
函数返回时true,将不会重新渲染组件
您也可以在导出语句中使用,例如:
export default memo(Modal, (prevState, nextState) => prevState.show === nextState.show) ;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3612 次 |
| 最近记录: |