如何在React 16.x中比较以前的上下文和当前的上下文?

时间:2019-03-05 08:50:28

标签: reactjs

在使用者子组件的生命周期方法中,是否可以将先前的上下文值与当前的上下文值进行比较?

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

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

2 个答案:

答案 0 :(得分:0)

通常,如果您要具有动态上下文,则其值很可能来自父组件的状态。 那么,为什么不检测状态变化而不是尝试检测提供程序的变化呢?

类似于react文档中的动态上下文示例:https://reactjs.org/docs/context.html#dynamic-context

答案 1 :(得分:0)

使用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更改时运行。因此,如果您真的不需要旧的contextValue做某事,则不需要useState