Aad*_*maa 1 javascript recoiljs
在 RecoilJS 中,与异步选择器的 React Suspense 无缝集成是一个很大的优势。然而,我在尝试标准化 Recoil 中缓存的数据时遇到了问题,同时仍然使用 Suspense。
为了通过示例解释该问题,用户可能有一组书籍。查询通过单个 API 调用填充集合,以获取所有用户的“最喜欢的”书籍。稍后的查询可能只请求一本书籍,该书可能已经或可能尚未通过最喜欢的书籍查询检索到。
我想要做的就是维护图书的规范化缓存,例如在由 bookId 键控的 AtomFamily 中,这样我就不会拥有使用不同查询提取的两本图书副本。但是,我遇到了一个问题,即我想对检索一本或多本书的任何一个查询使用 Suspense。使用 Recoil 来实现这一点的自然方法是使用异步选择器。但我不认为是否有一种方法可以标准化通过异步选择器获取的数据。
是否存在我忽略的模式,它允许我使用代表由共享的标准化 AtomFamily 支持的不同查询的异步选择器?
例如,如果我有这个 BAD 代码,它在我的状态中创建了重复的对象,那么我如何重新编写它以维护实际 Book 对象的共享缓存,并且如果当某个组件仍在获取查询时仍然使用 Suspense使用这个状态渲染?
查询1:通过选择器获取一组书籍:
const favoriteBooksSelector = selector({
key: 'MyFavoriteBooks',
get: async ({ get }) => {
const response = await allMyFavorityBooksDBQuery({
userID: get(currentUserIDState)
});
return response.books;
},
});
Run Code Online (Sandbox Code Playgroud)
查询 2:获取一本书,看起来像:
export const singleBookSelector = selectorFamily({
key: 'singleBookSelector',
get: (bookId: string) => async ({ get }) => {
const response = await singleBookDBQuery({
userID: get(currentUserIDState)
});
return response.book;
}
});
Run Code Online (Sandbox Code Playgroud)
要利用缓存,必须对其进行索引(键控)。对于您的示例情况,通过图书 ID 作为缓存的关键是明智的,因此 KV 缓存是一个合理的选择。在 JavaScript 中,aMap是这种缓存的自然选择。
下面,我编写了一个功能齐全的示例,说明如何实现此类缓存作为某些 RecoilatomFamily实例的主要来源。代码已注释,如果有任何不清楚的地方我可以提供更多解释。
\n\n\n显示增加的查询计数作为缓存有效性的证据。我还提供了 TypeScript Playground 中代码的链接以供评估。如果您想修改代码,您所需要做的就是将其复制到新答案中(或者只需将其复制并粘贴到本地文本编辑器中并将其另存为 HTML 文件,然后通过本地 http 服务器提供服务) 。
\n
<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/recoil@0.6.1/umd/recoil.min.js"></script><script src="https://unpkg.com/@babel/standalone@7.17.6/babel.min.js"></script><script>Babel.registerPreset(\'tsx\', {presets: [[Babel.availablePresets[\'typescript\'], {allExtensions: true, isTSX: true}]]});</script>\n<script type="text/babel" data-type="module" data-presets="tsx,react">\n\n// import ReactDOM from \'react-dom\';\n// import {default as React, Suspense, useEffect, useState, type ReactElement, type ReactNode} from \'react\';\n// import {atomFamily, RecoilRoot, useRecoilValue} from \'recoil\';\n\n// This Stack Overflow snippet demo uses UMD modules instead of the above import statments\nconst {Suspense, useEffect, useState} = React;\nconst {atomFamily, RecoilRoot, useRecoilValue} = Recoil;\n\ntype Book = {\n author: string;\n id: string;\n title: string;\n};\n\n\n// Database simulation:\n\n// The simulated database\nconst db = new Map<string, Book>();\n// Scraped from https://www.penguin.co.uk/articles/2018/100-must-read-classic-books.html#100\n(JSON.parse(`[{"author":"Jane Austen","title":"Pride and Prejudice","id":"BnuQKALlW6B6sZNU4bdaB"},{"author":"Harper Lee","title":"To Kill a Mockingbird","id":"UM3ms9hlnTbEmx44JknKc"},{"author":"F. Scott Fitzgerald","title":"The Great Gatsby","id":"hBl51iaNCQ8qZw5iec8hD"},{"author":"Gabriel\xc2\xa0Garc\xc3\xada M\xc3\xa1rquez","title":"One Hundred Years of Solitude","id":"CC9hIXCdEHR0beJlbMF_y"},{"author":"Truman Capote","title":"In Cold Blood","id":"l0iJfZNmNBfioHDnHARWQ"},{"author":"Jean Rhys","title":"Wide Sargasso Sea","id":"D0UY9kmrV6HbqlIMspVwn"},{"author":"Aldous Huxley","title":"Brave New World","id":"rK2ks0GbZBDQPns-ZDEyW"},{"author":"Dodie Smith","title":"I Capture The Castle","id":"flTB4dqKfg1PWcUI6KtH2"},{"author":"Charlotte Bronte","title":"Jane Eyre","id":"3x-S6EsNUTZ5l_sESamF_"},{"author":"Fyodor Dostoevsky","title":"Crime and Punishment","id":"ntH3G63fMVKUud6rRhDbY"},{"author":"Donna Tartt","title":"The Secret History","id":"ubrxbS1-7NEr_lml6I8Q3"},{"author":"Jack London","title":"The Call of the Wild","id":"friqBlVlEY3eg2cpkgUET"},{"author":"John Wyndham","title":"The Chrysalids","id":"wRMQGG1QYaeVXXP_ghl-x"},{"author":"Jane Austen","title":"Persuasion","id":"YoMqTM9PhAfctMBqSdz6P"},{"author":"Herman Melville","title":"Moby-Dick","id":"Kd0Oggfkf5AQPGBqpw_iE"},{"author":"C.S. Lewis","title":"The Lion, the Witch and the Wardrobe","id":"-jD0Ujt-r54xbKZ_7Jv59"},{"author":"Virginia Woolf","title":"To the Lighthouse","id":"1TJQYcP6_hwm2syHUH8Dv"},{"author":"Elizabeth Bowen","title":"The Death of the Heart","id":"dl1qbyM0cHdmYUHKhTyZk"},{"author":"Thomas Hardy","title":"Tess of the d\'Urbervilles","id":"_i6SLfaMpXRuhVqEH5Jhp"},{"author":"Mary Shelley","title":"Frankenstein","id":"ZPL-swiUogF-_gdabf9qv"},{"author":"Mikhail Bulgakov","title":"The Master and Margarita","id":"x0pw07n3o2KljHZM11isw"},{"author":"L. P. Hartley","title":"The Go-Between","id":"l0jHUSb4bY64k-l9Qed5Z"},{"author":"Ken Kesey","title":"One Flew Over the Cuckoo\'s Nest","id":"SCKsZTWD2QMsNomUie_Vf"},{"author":"George Orwell","title":"Nineteen Eighty-Four","id":"JscV73l2tSdm5W4kZSvZn"},{"author":"Thomas Mann","title":"Buddenbrooks","id":"f0XqwYfsWJ-w9J18b5FCD"},{"author":"John Steinbeck","title":"The Grapes of Wrath","id":"OnXfkmQEAL7sSQ3PgSV9z"},{"author":"Toni Morrison","title":"Beloved","id":"n3_aZgBlQkphqPTvmJGr6"},{"author":"P. G. Wodehouse","title":"The Code of the Woosters","id":"TzD6k5flXf8HMdfgSacMT"},{"author":"Bram Stoker","title":"Dracula","id":"_WPS6E_6uXVKWX0r2Sop6"},{"author":"J. R. R. Tolkien","title":"The Lord of the Rings","id":"bIzyksKmB0plzGwWI6h7l"},{"author":"Mark Twain","title":"The Adventures of Huckleberry Finn","id":"ctQZfUT_tsujBCdYkv4HA"},{"author":"Charles Dickens","title":"Great Expectations","id":"ULj9NAatfo8tCCe39YZTY"},{"author":"Joseph Heller","title":"Catch-22","id":"bOOUBZK7oFVDRrevxApvN"},{"author":"Edith Wharton","title":"The Age of Innocence","id":"ZJ8y0y-BbnaH5A9TulxgN"},{"author":"Chinua Achebe","title":"Things Fall Apart","id":"eahxg8sFYsudKEl9hocJv"},{"author":"George Eliot","title":"Middlemarch","id":"TLNUskf7TspVe3AOEV4nX"},{"author":"Salman Rushdie","title":"Midnight\'s Children","id":"0_DeHTlQpW4ffy-liu2R-"},{"author":"Homer","title":"The Iliad","id":"D9cyf2yCAwhnASsxGxtTd"},{"author":"William Makepeace Thackeray","title":"Vanity Fair","id":"YmXxLcLMYmuFkp39Q1aAa"},{"author":"Evelyn Waugh","title":"Brideshead Revisited","id":"p3D_ZtFdhT2Eytv7swOAZ"},{"author":"J.D. Salinger","title":"The Catcher in the Rye","id":"3Sf-5_lsdGVeiWJeSZZQI"},{"author":"Lewis Carroll","title":"Alice\xe2\x80\x99s Adventures in Wonderland","id":"TJJ6J8OHF5PRaiHLEcPdq"},{"author":"George Eliot","title":"The Mill on the Floss","id":"F6S5twxijUt7cSvuoSeKH"},{"author":"Anthony Trollope","title":"Barchester Towers","id":"0jYVd6dhiSF1tJYuIU8az"},{"author":"James Baldwin","title":"Another Country","id":"xRjGwu2vOQObLqbFccnw_"},{"author":"Victor Hugo","title":"Les Miserables","id":"GR24l64YVjFagi-SB1Y-H"},{"author":"Roald Dahl","title":"Charlie and the Chocolate Factory","id":"CAoAoALD3T8wxX0Eevabi"},{"author":"S. E. Hinton","title":"The Outsiders","id":"XYhNMkKTKsh9aNGh24fvZ"},{"author":"Alexandre Dumas","title":"The Count of Monte Cristo","id":"Igcm-Wxq2Uf8vKjBr-D7j"},{"author":"James Joyce","title":"Ulysses","id":"GiianKDQPQVTIaFoFhy6H"},{"author":"John Steinbeck","title":"East of Eden","id":"belUus-Sta74zWfjTiuMW"},{"author":"Fyodor Dostoyevsky","title":"The Brothers Karamazov","id":"wp9JOJ0B8lKmxG0siRuR4"},{"author":"Vladimir Nabokov","title":"Lolita","id":"tvnoXyLsd-PtVmiwZLnM8"},{"author":"Frances Hodgson Burnett","title":"The Secret Garden","id":"VZyJI95JMwkj4rJOJbzzn"},{"author":"Evelyn Waugh","title":"Scoop","id":"QYgFDNe1S0x5V_ub-Vc-S"},{"author":"Charles Dickens","title":"A Tale of Two Cities","id":"G0FUeqOiLuNnBNEr4XPD2"},{"author":"George\xc2\xa0Grossmith\xc2\xa0and Weedon Grossmith","title":"Diary of a Nobody","id":"PLi0tMjdAZI54P3U02B2N"},{"author":"Leo Tolstoy","title":"Anna Karenina","id":"E0OlPZ9F8Z3rsEmGihW-0"},{"author":"Alessandro Manzoni","title":"The Betrothed","id":"hPHRkfbcMUeJUejXy7spa"},{"author":"Virginia Woolf","title":"Orlando","id":"FSzptVHC-ICRl0tlPhS-O"},{"author":"Ayn Rand","title":"Atlas Shrugged","id":"CdzIlNo9jp5CDAP5BEwLi"},{"author":"H. G. Wells","title":"The Time Machine","id":"dQn4oEs0hqgfuaFR13S-o"},{"author":"Sun-Tzu","title":"The Art of War","id":"LZwoJLEtLv4Dx2QnUBvwM"},{"author":"John Galsworthy","title":"The Forsyte Saga","id":"p9hOPd4gC7PKX9bbp8JVZ"},{"author":"John Steinbeck","title":"Travels with Charley","id":"c3LtQi5_p-XSF2JSfPOjq"},{"author":"Henry Miller","title":"Tropic of Cancer","id":"iFILNdFzltGXugvwpUjSS"},{"author":"D. H. Lawrence","title":"Women in Love","id":"gYf7mAVCM_SX5e3NDwc9y"},{"author":"Paul Scott","title":"Staying On","id":"gZYOkRz4APlcDGNH5onYD"},{"author":"Kenneth Grahame","title":"The Wind in the Willows","id":"epTCvsskVjm3vnomZCPRw"},{"author":"Willa Cather","title":"My \xc3\x81ntonia","id":"wWoBKiKEQ6KpwigH2RtMQ"},{"author":"Emily Bront\xc3\xab","title":"Wuther