MOBX REACT:定义观察者钩
我正在尝试在一个依赖MOBX可观察到的MOBX项目中定义自己的钩子。 但是,由于观察者()必须返回组件,因此无法用observer()包裹钩子。 有没有办法定义观察者挂钩?
例子:
// not working because observer must return a component
const useFindSuggestion = observer(({ target, node, suggestionsStore }: LinkSuggestionWrapperProps) => {
const [suggestions, setSuggestions] = useState<IDocumentInfo[]>([]);
useEffect(() => {
const suggestions = suggestionsStore.getRelevantSuggestions(node, target).filter((s) => s.documentId !== node.target);
setSuggestions(suggestions);
}, []);
return { suggestions };
});
I'm trying to define my own hooks in a MobX project which depend on mobx observables.
But it's not possible to wrap a hook with observer() because observer() must return a component.
Is there a way to define observer hooks?
Example:
// not working because observer must return a component
const useFindSuggestion = observer(({ target, node, suggestionsStore }: LinkSuggestionWrapperProps) => {
const [suggestions, setSuggestions] = useState<IDocumentInfo[]>([]);
useEffect(() => {
const suggestions = suggestionsStore.getRelevantSuggestions(node, target).filter((s) => s.documentId !== node.target);
setSuggestions(suggestions);
}, []);
return { suggestions };
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案:在挂钩中使用自动运输
https://mobx.js.org/reaect-react-integration.html#useefect.html#useefect
示例: https:// codesandbox。 io/s/s/minimal-mobx-reAct-project-forked-8gnxgt?file =/index.js
Solution: use autorun within hook
https://mobx.js.org/react-integration.html#useeffect
Example: https://codesandbox.io/s/minimal-mobx-react-project-forked-8gnxgt?file=/index.js