即使不使用上下文,子组件仍会重新呈现

Child component is still re-rendered even if it is not consuming the context

我的 React 代码中有以下结构:

const Parent: React.FC<ParentProps> = (props) => {
    const [value1, setValue1] = useState<any>(null);

    return (
        <div>
            <SomeContextProvider
                contextElem1={value1}
                contextElem2={value2}
            >
                ...some code here

                <Child
                    prop1={value3}
                    prop2={value4}
                />
            </SomeContextProvider>
        </div>
    );
}
 
export default Parent;
const Child: React.FC<ChildProps> = ({ prop1, prop2 }) => {
    return (
        <div>
            {prop1} {prop2}
        </div>
    );
}
 
const propsAreEqual = (prevProps: ChildProps, nextProps: ChildProps) => {
    return true;
}


export default React.memo(Child, propsAreEqual);

如您所见:

场景如下:

为什么 Child 在不使用上下文的情况下被重新渲染? React.memo 不是应该防止重新渲染吗?我对这些概念有什么误解?

我认为你错了。我将您的代码复制到 CodeSandbox 中并对其进行了修改,以便实际构建。 child 不会在 parent re-renders 时呈现,因为您已将其包装在 React.memo() 中。 (如果我删除 memo(),那么 child 会 re-render。)

https://codesandbox.io/s/misty-feather-tl3p6?file=/src/App.js

如果您的代码触发了 re-renders,这可能是因为您对 propsAreEqual 函数的特定实现或您为 value3value4.[=15 传递的值=]