【问题标题】:How to compare previous context with current context in React 16.x?如何在 React 16.x 中比较以前的上下文和当前的上下文?
【发布时间】:2019-03-05 08:50:28
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    使用 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

    【讨论】:

      【解决方案2】:

      通常,如果您要使用动态上下文,它的值很可能来自父组件的状态。 那么为什么不检测状态的变化,而不是尝试检测 Provider 的变化呢?

      就像反应文档中动态上下文的示例一样:https://reactjs.org/docs/context.html#dynamic-context

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-08
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多