簡體   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