Spe*_*gum 4 javascript reactjs react-context
我试图在我的应用程序中使用新的Context API,并且看起来每次更新上下文时,它都会重新渲染与其连接的任何组件。我有一个沙盒演示设置,可以查看代码和工作问题。当您输入内容时-按钮上下文将呈现,反之亦然。我最初的想法是,如果您输入输入内容,那么只会打印出输入内容。
这是如何运作的还是我错过了什么?谢谢,斯宾塞
我避免使用react context API重新呈现的方式:
const MyComponent = React.memo(({
somePropFromContext,
otherPropFromContext,
someRegularPropNotFromContext
}) => {
... // regular component logic
return(
... // regular component return
)
});
Run Code Online (Sandbox Code Playgroud)
function select(){
const { someSelector, otherSelector } = useContext(MyContext);
return {
somePropFromContext: someSelector,
otherPropFromContext: otherSelector,
}
}
Run Code Online (Sandbox Code Playgroud)
function connect(WrappedComponent, select){
return function(props){
const selectors = select();
return <WrappedComponent {...selectors} {...props}/>
}
}
Run Code Online (Sandbox Code Playgroud)
import connect from 'path/to/connect'
const MyComponent ... //previous code
function select() ... //previous code
export default connect(MyComponent, select)
Run Code Online (Sandbox Code Playgroud)
<MyComponent someRegularPropNotFromContext={something} />
Run Code Online (Sandbox Code Playgroud)
MyComponent仅在上下文中的props props用新值更新时才会重新渲染,如果值相同,则不会重新渲染。另外,它还避免了根据上下文中未使用的上下文重新渲染任何其他值MyComponent。select中的代码将在每次上下文更新时执行,但由于它没有任何作用,所以可以,因为不会MyComponent浪费任何重新渲染。
| 归档时间: |
|
| 查看次数: |
2447 次 |
| 最近记录: |