[英]Recoil: Passing a long-lived client object to a selector
Coming from react-redux
/ redux-thunk
, there is a nice way of instantiating a client object once, passing it to ThunkMiddleware, and retrieving it in thunks:来自
react-redux
/ redux-thunk
,有一种很好的方法来实例化客户端 object 一次,将其传递给 ThunkMiddleware,并在 thunk 中检索它:
// This is the instance I want during async calls
const myApiClient = new MyApiClient();
const store = createStore(
reducer,
applyMiddleware(thunk.withExtraArgument(myApiClient))
);
Then in my thunk definitions:然后在我的thunk定义中:
const fetchSomething = (id) => {
return (dispatch, getState, myApiClient) => {
// It's the same instance!
return myApiClient.fetchSomething(id)
.then((res) ....);
}
}
In Recoil I can see no way of achieving something similar: as far as I can see, examples in the documentation assume that the body of atoms / selectors can be executed without any context instantiated externally.在 Recoil 中,我看不到实现类似的方法:据我所知,文档中的示例假设原子/选择器的主体可以在没有任何外部实例化的上下文的情况下执行。
Since it seems unlikely that this was not a consideration when designing Recoil, I'm curious what I've missed here?由于在设计 Recoil 时似乎不太可能不考虑这一点,我很好奇我在这里错过了什么?
You can use the useRecoilCallback
hook, which basically offers something similar, but not as middleware.您可以使用
useRecoilCallback
钩子,它基本上提供了类似的东西,但不是作为中间件。 Since recoil does not have a global cohesive state in a strict sense, there is no real middleware.由于 recoil 没有严格意义上的全局内聚 state,因此没有真正的中间件。 Think of it as a component tree like react, but for state atoms.
将其视为类似于 react 的组件树,但对于 state 原子。 You can connect those via selectors and query and set them via react components, but recoil itself doesn't really know about all the atoms (you can even create atoms during runtime if you want to).
您可以通过选择器连接它们并通过反应组件查询和设置它们,但反冲本身并不真正了解所有原子(如果您愿意,您甚至可以在运行时创建原子)。
So how you would go about that is something like this:那么你将如何 go 是这样的:
const myApiClient = new MyApiClient();
// Can also be returned by a hook.
const thunkWithExtraArgument = useRecoilCallback(({snapshot, set}) => async (myApiClient) => {
const res = myApiClient.fetchSomething(id);
set(atom, res.json());
}, []);
// ... Somewhere else in a component
thunkWithExtraArgument(myApiClient);
For the recoil callback hook check this out: https://recoiljs.org/docs/api-reference/core/useRecoilCallback对于反冲回调挂钩,请查看: https://recoiljs.org/docs/api-reference/core/useRecoilCallback
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.