繁体   English   中英

Recoil:将长期存在的客户端 object 传递给选择器

[英]Recoil: Passing a long-lived client object to a selector

来自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))
);

然后在我的thunk定义中:

const fetchSomething = (id) => {
    return (dispatch, getState, myApiClient) => {
        // It's the same instance!
        return myApiClient.fetchSomething(id)
                .then((res) ....);
    }
}

在 Recoil 中,我看不到实现类似的方法:据我所知,文档中的示例假设原子/选择器的主体可以在没有任何外部实例化的上下文的情况下执行。

由于在设计 Recoil 时似乎不太可能不考虑这一点,我很好奇我在这里错过了什么?

您可以使用useRecoilCallback钩子,它基本上提供了类似的东西,但不是作为中间件。 由于 recoil 没有严格意义上的全局内聚 state,因此没有真正的中间件。 将其视为类似于 react 的组件树,但对于 state 原子。 您可以通过选择器连接它们并通过反应组件查询和设置它们,但反冲本身并不真正了解所有原子(如果您愿意,您甚至可以在运行时创建原子)。

那么你将如何 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);

对于反冲回调挂钩,请查看: https://recoiljs.org/docs/api-reference/core/useRecoilCallback

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM