我正在尝试在一个功能组件中实现shouldComponentUpdate方法。
以下是最初的方法(类完整组件)
shouldComponentUpdate(nextProps, nextState) {
return (
this.state.isSelected || nextState.isSelected !== this.state.isSelected
);
}但是,有了“反应备忘录”,我似乎只能访问prevProps和nextProps,而不能访问nextState。
memo(..., (prevProps, nextProps) => true);如何在功能组件中访问nextState来模拟shouldComponentUpdate?
发布于 2021-05-16 10:27:53
“反应备忘录”的目的是只检查道具何时变化,而不是状态。如果您尝试这样做,您就违反了规则--纯组件功能的目的。您想要的是使用效果挂钩:
useState(()=>{
//...
}, [state that you want to check])因此,对于这一要求,避免使用备忘录,因为它不是纯组件。组件将在状态更改时呈现,因此没有纯功能。
在执行shouldComponentUpdate时,不需要传递依赖数组,只需检查条件,然后将useEffect作为shouldComponentUpdate使用。
useState(()=>{
//check condition here and do logic
})发布于 2022-02-28 17:24:44
你可以用这个:
const Component = {....}
const handleMemoProps = (prevProps, nextProps) => {
return true or false
}
export default React.memo(Component, handleMemoProps)https://stackoverflow.com/questions/67555334
复制相似问题