solid.js:如何将UseContext放入来自外部事件的提供商中
const CounterContext = createContext();
export function CounterProvider(props) {
const [count, setCount] = createSignal(0),
store = [
count
];
return (
<CounterContext.Provider value={store}>
{props.children}
</CounterContext.Provider>
);
}
export function useCounter() { return useContext(CounterContext); }
在提供商之外,我想在提供商之外使用此usecounter
,例如settimeout
或传入的websocket消息。
setTimeout(() => {
const [count] = useCounter();
createEffect(on(count, () => {
console.log(count)
}))
})
这似乎是一个坏主意,但是我在应用程序代码中有这个,我不知道如何重组我的代码以避免这种情况。
const CounterContext = createContext();
export function CounterProvider(props) {
const [count, setCount] = createSignal(0),
store = [
count
];
return (
<CounterContext.Provider value={store}>
{props.children}
</CounterContext.Provider>
);
}
export function useCounter() { return useContext(CounterContext); }
I want to use this useCounter
outside of the provider, after an external event like a setTimeout
or an incoming Websocket message.
setTimeout(() => {
const [count] = useCounter();
createEffect(on(count, () => {
console.log(count)
}))
})
This seems like a bad idea, but I have this in my application code, and I don't know how to restructure my code to avoid this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
runwithowner
运行异步代码以访问组件的上下文。用
runwithowner
将其包裹起来还使其与组件旁边的处置中创建的计算 - 如果您在根外创建计算,则永远不会被处置。Playground link: https://playground.solidjs.com/?hash=1366672288& ;版本= 1.3.16
You can run asynchronous code with
runWithOwner
to have access to the component's context.Wrapping it with
runWithOwner
also makes the computations created within dispose alongside the component - if you create a computation outside a root, it will never be disposed.Playground link: https://playground.solidjs.com/?hash=1366672288&version=1.3.16
通常,如果可能的话,我会考虑在提供商下或在受保护的主要渲染下的效果下获取usecontext呼叫。是的,您可以使用更高级的API,例如Runwithowner,但是如果您无法做到这一点,则可能会导致其他麻烦。
通常,修复程序涉及创建一个信号,该信号可以同步您想要的动态行为,然后通过从超时设置信号来触发它。
Generally I would look at getting the useContext call under the provider if possible or under a effect under the main rendering that is guarded. Yes you could use more advanced APIs like runWithOwner, but it probably will lead to other hiccups later if things are structured in a way you wouldn't be able to do that.
Normally the fix involves creating a signal that wires up the dynamic behavior you want synchronously, and then triggers it by setting the signal from the timeout.