为 React Context 实现 useSelector 等价物? [英] Implement useSelector equivalent for React Context?

查看:22
本文介绍了为 React Context 实现 useSelector 等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多文章展示了如何用上下文和钩子替换 Redux(参见 这个来自 Kent Dodds,例如).基本思想是通过上下文使您的全局状态可用,而不是将其放在 Redux 存储中.但是这种方法有一个大问题:只要上下文发生任何更改,订阅上下文的组件就会重新呈现,无论您的组件是否关心刚刚更改的状态部分.对于函数式组件,React-redux 通过 useSelector hook 解决了这个问题.所以我的问题是:是否可以创建像 useSelector 这样的钩子,它会抓取一段上下文而不是 Redux 存储,具有与 useSelector 相同的签名,并且就像 useSelector 一样,只会在选择"部分上下文发生了变化?

There's a bunch of articles out there that show how Redux can be replaced with context and hooks (see this one from Kent Dodds, for instance). The basic idea is to make your global state available through a context instead of putting it inside a Redux store. But there's one big problem with that approach: components that subscribe to the context will be rerendered whenever any change happens to the context, regardless of whether or not your component cares about the part of the state that just changed. For functional components, React-redux solves this problem with the useSelector hook. So my question is: can a hook like useSelector be created that would grab a piece of the context instead of the Redux store, would have the same signature as useSelector, and, just like useSelector, would only cause rerenders to the component when the "selected" part of the context has changed?

(注意:React Github 页面上的这个讨论表明它不能完成)

(note: this discussion on the React Github page suggests that it can't be done)

推荐答案

不,这不可能.每当您将新的上下文值放入提供程序时,所有 使用者都会重新渲染,即使他们只需要该上下文值的一部分.

No, it's not possible. Any time you put a new context value into a provider, all consumers will re-render, even if they only need part of that context value.

这是特别是我们放弃使用上下文的原因之一在 React-Redux v6 中传播状态更新,并在 v7 中切换回使用直接存储订阅.

社区编写的 React RFC 来将选择器添加到上下文,但没有任何指示React 团队实际上将完全实现该 RFC.

There's a community-written React RFC to add selectors to context, but no indication the React team will actually pursue implementing that RFC at all.

这篇关于为 React Context 实现 useSelector 等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆