React Context API似乎重新渲染每个组件

问题描述 投票:2回答:2

我正在尝试在我的应用程序中使用新的Context API,看起来每次更新上下文时,它都会重新呈现连接到它的任何组件。我有一个沙盒演示设置来查看代码和工作问题。当您输入输入时 - 按钮上下文被渲染,反之亦然。我最初的想法是,如果输入输入,只会输出输入上下文。

DEMO

这是它的工作原理还是我错过了什么?谢谢,斯宾塞

javascript reactjs react-context
2个回答
1
投票

这是预期的行为。作为消费者的组件在其提供者数据更新时重新呈现。此外,shouldComponentUpdate钩子不适用于消费者。

引用React的内容API:

作为提供者后代的所有消费者将在提供者的价值支柱发生变化时重新呈现。从Provider到其后代使用者的传播不受shouldComponentUpdate方法的约束,因此即使祖先组件退出更新,Consumer也会更新。

有关更多信息,请查看here


3
投票

我避免使用react context API重新渲染的方式:

First I write my component as pure functional component:

const MyComponent = React.memo(({
    somePropFromContext,
    otherPropFromContext, 
    someRegularPropNotFromContext  
}) => {
    ... // regular component logic
    return(
        ... // regular component return
    )
});

Then I write a function to select props from context:

function select(){
  const { someSelector, otherSelector } = useContext(MyContext);
  return {
    somePropFromContext: someSelector,
    otherPropFromContext: otherSelector,
  }
}

I have my connect HOC wrote:

function connect(WrappedComponent, select){
  return function(props){
    const selectors = select();
    return <WrappedComponent {...selectors} {...props}/>
  }
}

All together

import connect from 'path/to/connect'

const MyComponent ... //previous code

function select() ... //previous code

export default connect(MyComponent, select)

Usage

<MyComponent someRegularPropNotFromContext={something} />

Demo

Demo on codesandbox

Conclusion

MyComponent只有在具有新值的上下文更新中才会重新呈现,如果值相同,则不会重新呈现。此外,它还避免重新渲染MyComponent中未使用的上下文中的任何其他值。 select中的代码将在每次上下文更新时执行,但由于它什么也没做,所以没问题,因为没有浪费重新渲染MyComponent

© www.soinside.com 2019 - 2024. All rights reserved.