首页 > 解决方案 > 如何在 React 16.x 中比较以前的上下文和当前的上下文?

问题描述

有没有办法在消费者子组件的生命周期方法中将先前的上下文值与当前的上下文值进行比较?

如果没有办法做到这一点,是否有任何其他解决方法或替代解决方案?

仅供参考:我正在使用反应 v16.8.1

标签: reactjs

解决方案


使用 HOC:

const withContext = Wrapped => props => (
    <SomeContext.Consumer>
        {value => <Wrapped {...props} contextValue={value}/>}
    </SomeContext.Consumer>
);

const MyComponent = withContext(class extends React.Component {
    ...
    componentDidUpdate(prevProps) {
        if (prevProps.contextValue !== this.props.contextValue) {
            ...
        }
    }
    ...
});

使用钩子:

function MyComponent(props) {
    ...
    const contextValue = useContext(SomeContext);
    const [oldContextValue, saveContextValue] = useState(contextValue);
    useEffect(() => {
        console.log(oldContextValue, contextValue);
        saveContextValue(contextValue);
    }, [contextValue]);
    ...
}

请注意,useEffect仅在第一次渲染和contextValue更改时运行。所以如果你真的不需要 oldcontextValue来做某事,你就不需要useState.


推荐阅读