如何使用观察者来包装反应自定义钩子?
在我的项目中,我创建了一个自定义反应钩子,需要使用存储的可观察状态来存储 useEffect 的依赖项:
我的示例自定义钩子:
const useFoo = (() => {
const { count } = store;
useEffect (() => {
//do something here
},[count])
})
通常我们必须包装observer()组件以使其重新渲染,但observer()不接受包装自定义钩。我已经在这个 问题 但这并没有明确回答我。
所以任何人都可以给我一个解决方案来做到这一点。我意识到自定义钩子应该与数据隔离以便可重用,但就我而言,如果我有这个问题的解决方案,我将节省大量时间来重构代码。多谢
In my project, I create a custom react hook that needs to use observable state in store for dependencies of useEffect:
My example custom hook:
const useFoo = (() => {
const { count } = store;
useEffect (() => {
//do something here
},[count])
})
Normally we must wrap observer() the component to make it rerender but observer() does not accept wrap custom hook. I have already referred to another question in this question but this isn't clearly answered to me.
So Anyone can give me a solution to do this. I realize custom hook should be isolated from data to be reusable but in my case, I will save a lot of time to refactor code if I have solution for this problem. Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在
useFoo
中取消引用的可观察数据将由使用它的observer
组件获取,因此您的observer
组件使用useFoo< /code> 将按预期重新渲染。
示例
The observable data you dereference in
useFoo
will be picked up by theobserver
components that use it, so yourobserver
components usinguseFoo
will re-render as expected.Example