React Hooks 功能组件,具有基于 state/prop 值的受控渲染
React Hooks function component with controlled rendering based on state/prop values
能够在 React Class 组件上使用 shouldComponentUpdate
的好处之一是能够根据条件控制渲染,而不仅仅是 state/prop 中的更改值。
在函数组件中使用 React Hook 进行此优化的首选方法是什么?
在下面的示例中,如果 class 组件处于(或保持)关闭状态,即使它有新的子组件也不会重新呈现。
class DrawerComponent extends React.Component {
static propTypes = {
children: PropTypes.any,
}
state = {
isOpen: false,
}
// only re-render if the drawer is open or is about to be open.
shouldComponentUpdate(nextProps, nextState) {
return this.state.isOpen || nextState.isOpen;
}
toggleDrawer = () => {
this.setState({isOpen: !this.state.isOpen});
};
render() {
return (
<>
<div onClick={this.toggleDrawer}>
Drawer Title
</div>
<div>
{this.state.isOpen ? this.props.children : null}
</div>
</>
)
}
}
函数组件对应(未优化):
function DrawerComponent({ children }) {
const [isOpen, setIsOpen] = useState(false);
function toggle() {
setIsOpen(!isOpen);
}
return (
<>
<div onClick={toggle}>
Drawer Title
</div>
<div>{isOpen ? children : null}</div>
</>
);
}
在这个例子中,我认为没有必要进行 shouldComponentUpdate
优化。它已经很快了,因为当抽屉关闭时你没有渲染 children
。 运行 功能组件的成本可以忽略不计。
也就是说,如果您确实想在功能组件中实现等效行为,您可以使用 React.memo
并提供自定义 areEqual
函数:https://reactjs.org/docs/react-api.html#reactmemo.
能够在 React Class 组件上使用 shouldComponentUpdate
的好处之一是能够根据条件控制渲染,而不仅仅是 state/prop 中的更改值。
在函数组件中使用 React Hook 进行此优化的首选方法是什么?
在下面的示例中,如果 class 组件处于(或保持)关闭状态,即使它有新的子组件也不会重新呈现。
class DrawerComponent extends React.Component {
static propTypes = {
children: PropTypes.any,
}
state = {
isOpen: false,
}
// only re-render if the drawer is open or is about to be open.
shouldComponentUpdate(nextProps, nextState) {
return this.state.isOpen || nextState.isOpen;
}
toggleDrawer = () => {
this.setState({isOpen: !this.state.isOpen});
};
render() {
return (
<>
<div onClick={this.toggleDrawer}>
Drawer Title
</div>
<div>
{this.state.isOpen ? this.props.children : null}
</div>
</>
)
}
}
函数组件对应(未优化):
function DrawerComponent({ children }) {
const [isOpen, setIsOpen] = useState(false);
function toggle() {
setIsOpen(!isOpen);
}
return (
<>
<div onClick={toggle}>
Drawer Title
</div>
<div>{isOpen ? children : null}</div>
</>
);
}
在这个例子中,我认为没有必要进行 shouldComponentUpdate
优化。它已经很快了,因为当抽屉关闭时你没有渲染 children
。 运行 功能组件的成本可以忽略不计。
也就是说,如果您确实想在功能组件中实现等效行为,您可以使用 React.memo
并提供自定义 areEqual
函数:https://reactjs.org/docs/react-api.html#reactmemo.