據(jù)更新完全指南:從 GraphQL Mutations 到 Store 命令式修改)
前端開發(fā)工具【免費下載鏈接】relayRelay is a JavaScript framework for building>項目地址https://gitcode.com/gh_mirrors/relay29/relay點擊查看免費下載在 Relay 中獲取數(shù)據(jù)只是數(shù)據(jù)生命周期的一半。本指南基于 Relay 19 版本文檔中 updating-data 章節(jié)入口文檔 展開系統(tǒng)講解如何有意地修改 Relay 本地數(shù)據(jù)存儲Relay store以及服務(wù)器端數(shù)據(jù)包括使用useMutation/commitMutation執(zhí)行 GraphQL Mutations、通過updater命令式改寫 store、借助optimisticResponse實現(xiàn)樂觀更新、用ConnectionHandler維護連接Connections以及通過commitLocalUpdate/commitPayload做純本地更新。讀完本文你將掌握一套從發(fā)出寫請求到本地 store 與 UI 保持一致的完整數(shù)據(jù)更新方案。從獲取數(shù)據(jù)到更新數(shù)據(jù)為什么需要專門討論在 guided-tour 的獲取數(shù)據(jù)章節(jié) 中我們討論了如何用 GraphQL 查詢獲取數(shù)據(jù)。需要強調(diào)的是獲取數(shù)據(jù)這件事附帶地也可能修改 Relay 本地 store 中的數(shù)據(jù)——如果查詢返回的數(shù)據(jù)與 store 中已有緩存不一致Relay 會合并并覆蓋。但這不是有意的寫入行為因此我們還需要一套機制來顯式地、受控地更新本地數(shù)據(jù)與服務(wù)端數(shù)據(jù)這正是 updating-data 系列文檔的主題。在進入細節(jié)之前先明確一個貫穿全文的核心概念:::noteRelay store是關(guān)聯(lián)于某個 Relay environment 的 GraphQL 數(shù)據(jù)緩存其中保存的是應(yīng)用執(zhí)行過程中遇到過的即被查詢過的數(shù)據(jù)。所有本地寫入最終都會落到這個 store 上并驅(qū)動依賴這些數(shù)據(jù)的組件重渲染。 :::Relay 更新數(shù)據(jù)的整體能力圖譜對應(yīng)本倉庫 versioned docs 中 updating-data 目錄如下GraphQL Mutations通過useMutation/commitMutation執(zhí)行服務(wù)端寫操作并將響應(yīng)寫回 storeGraphQL Subscriptions通過useSubscription/requestSubscription訂閱服務(wù)端事件流隨事件更新數(shù)據(jù)命令式修改 store 數(shù)據(jù)在updater中使用readUpdatableFragment/readUpdatableQuery精確改寫標量字段命令式修改鏈接字段通過assignable片段在 store 中重新指定記錄間的鏈接關(guān)系更新連接Connections向連接增刪邊可用聲明式指令或ConnectionHandler手工操作本地數(shù)據(jù)更新commitLocalUpdate與commitPayload兩類純本地 API客戶端專屬數(shù)據(jù)通過 client schema extensions 在客戶端擴展 GraphQL schema類型安全 updaters FAQ解釋updatable/readUpdatableQuery等類型安全 API 的設(shè)計動機與約束。下面按由簡到繁的順序逐一展開。GraphQL Mutations在 Relay 中聲明并執(zhí)行寫操作在 GraphQL 中服務(wù)端數(shù)據(jù)通過mutation更新。Mutation 是一種可讀可寫的服務(wù)端操作它既在后臺修改數(shù)據(jù)又允許在同一次請求中查詢修改后的數(shù)據(jù)。編寫 MutationMutation 的寫法與 query 幾乎一致只是關(guān)鍵字換成mutationmutation FeedbackLikeMutation($input: FeedbackLikeData!) { feedback_like(data: $input) { feedback { id viewer_does_like like_count } } }上面的 mutation 修改服務(wù)端數(shù)據(jù)把指定的Feedback對象標記為已點贊feedback_like是mutation 根字段mutation root field負責在后臺更新數(shù)據(jù)Mutation 的處理分為兩個獨立步驟先處理服務(wù)端更新再執(zhí)行查詢。這保證了響應(yīng)中只會出現(xiàn)已經(jīng)被本次 mutation 更新過的數(shù)據(jù)。注查詢本身也是這種外層先于內(nèi)層的計算順序只是約定上 mutation 頂層字段帶有副作用mutation 根字段返回一個具體的 GraphQL 類型該類型暴露了可以在 mutation 響應(yīng)中查詢的數(shù)據(jù)。本例查詢的是更新后的 feedback 對象包括最新的like_count和viewer_does_like表示當前 viewer 是否已點贊。一次成功響應(yīng)的示例{ feedback_like: { feedback: { id: feedback-id, viewer_does_like: true, like_count: 1, } } }在 Relay 中同樣用graphql標簽來聲明 mutation并且 mutation 可以像 query/fragment 一樣引用 GraphQL variablesconst {graphql} require(react-relay); const feedbackLikeMutation graphql mutation FeedbackLikeMutation($input: FeedbackLikeData!) { feedback_like(data: $input) { feedback { id viewer_does_like like_count } } } ;使用useMutation執(zhí)行 mutationRelay 提供了commitMutation和useMutation兩個 API 來執(zhí)行 mutation。先看 Hooks 風格的useMutationimport type {FeedbackLikeData, LikeButtonMutation} from LikeButtonMutation.graphql; const {useMutation, graphql} require(react-relay); function LikeButton({ feedbackId: string, }) { const [commitMutation, isMutationInFlight] useMutationLikeButtonMutation( graphql mutation LikeButtonMutation($input: FeedbackLikeData!) { feedback_like(data: $input) { feedback { viewer_does_like like_count } } } ); return button onClick{() commitMutation({ variables: { input: {id: feedbackId}, }, })} disabled{isMutationInFlight} Like /button }這段代碼的要點useMutation的唯一參數(shù)是一個包含 mutation 的graphql字面量它返回一個二元組commit 回調(diào)接受一個UseMutationConfig配置對象與布爾值isMutationInFlight表示是否有 mutation 在途可用于禁用按鈕useMutation還接受一個 Flow 類型參數(shù)如LikeButtonMutation。該類型由 Relay compiler 生成的graphql.js文件導出。最佳實踐是始終提供這個類型參數(shù)——提供后UseMutationConfig也會被靜態(tài)類型化調(diào)用commitMutation后Relay 發(fā)起網(wǎng)絡(luò)請求執(zhí)行feedback_like字段服務(wù)端記錄用戶已點贊并回選更新后的viewer_does_like與like_count。由于Feedback類型包含id字段Relay compiler 會自動為其補選id響應(yīng)到達后Relay 在 store 中找到id匹配的 feedback 記錄并更新字段值任何選擇過這些字段的組件都會在值變化時自動重渲染。類型命名規(guī)則參數(shù)類型FeedbackLikeData的名字派生自頂層 mutation 字段名即feedback_like同樣由生成的graphql.js文件導出。源碼視角useMutation的實現(xiàn)在 React 側(cè)useMutation的實現(xiàn)位于 packages/react-relay/relay-hooks/useMutation.js。其中UseMutationConfig類型L33-L51完整定義了可以傳給 commit 回調(diào)的配置項configs?: ArrayDeclarativeMutationConfig聲明式 mutation 配置舊式;onError?: ?(error: Error) void與onCompleted?: ?(response, errors) void成功/失敗回調(diào);optimisticResponse樂觀響應(yīng)依賴raw_response_type指令獲得類型;optimisticUpdater?: ?SelectorStoreUpdater與updater?: ?SelectorStoreUpdater樂觀/常規(guī) updater 函數(shù);uploadables?: UploadableMap文件上傳;variables必填的 mutation 變量。hook 簽名L66-L75返回[(UseMutationConfigInternal) Disposable, boolean]。其內(nèi)部邏輯L107-L120是調(diào)用 commit 時先setMutationInFlight(true)然后委托給commitMutationFn默認是relay-runtime導出的commitMutation并在onCompleted/onError時通過cleanup把該 disposable 從在途集合中移除、更新isMutationInFlight。這正是按鈕 disabled 狀態(tài)隨請求生命周期變化的實現(xiàn)基礎(chǔ)。讓組件響應(yīng) mutation手動選字段 vs 展開 fragment上例手動選擇了viewer_does_like與like_count選擇這些字段的組件會在值變化時重渲染。但更推薦的做法是展開對應(yīng)組件的 fragment——因為組件選擇的數(shù)據(jù)集是會演進的要求開發(fā)者記住所有可能影響自己數(shù)據(jù)的 mutation并持續(xù)維護正是 Relay 想要避免的全局推理負擔。mutation FeedbackLikeMutation($input: FeedbackLikeData!) { feedback_like(data: $input) { feedback { ...FeedbackDisplay_feedback ...FeedbackDetail_feedback } } }這樣FeedbackDisplay與FeedbackDetail組件所選字段會在 mutation 執(zhí)行后一并刷新組件始終保持一致狀態(tài)。:::note 展開 fragment 通常優(yōu)于 mutation 完成后再手動 refetch更新后的數(shù)據(jù)可以在單次往返中取回。 :::在 mutation 完成或失敗時執(zhí)行回調(diào)UseMutationConfig支持以下回調(diào)onCompletedmutation 成功完成時執(zhí)行參數(shù)是 mutation 響應(yīng)在 fragment 展開邊界處截斷。傳入的值是在 updaters 與聲明式 mutation 指令應(yīng)用之后、從 store 中讀出的 mutation fragment——因此未展開 fragment 內(nèi)的數(shù)據(jù)不會包含其中被刪除的記錄如deleteRecord刪除的可能為nullonErrormutation 失敗時執(zhí)行參數(shù)是發(fā)生的錯誤對象。聲明式 mutation 指令刪除記錄與操作連接除了手寫 updaterRelay 提供了一組聲明式指令讓常見更新幾乎零代碼。刪除記錄deleteRecord想在 mutation 響應(yīng)中把某個對象從 store 刪除可在其id字段上加deleteRecordmutation DeletePostMutation($input: DeletePostData!) { delete_post(data: $input) { deleted_post { id deleteRecord } } }連接增刪appendEdge/prependEdge/appendNode/prependNode/deleteEdge這些指令以及deleteEdge可以作用在 mutation、subscription 甚至 query 的字段上具體細節(jié)見 Updating Connections 文檔此處先給出要點appendEdge/prependEdge作用于返回單個 edge 或 edge 列表的字段把選中的邊追加到connections參數(shù)指定各連接的末尾/開頭appendNode/prependNode作用于返回單個 node 或 node 列表的字段把選中的節(jié)點包裝成邊后追加/前插deleteEdge作用于返回ID或[ID]的字段刪除各連接中節(jié)點 id 匹配的邊它們都接受connections參數(shù)——一個包含連接 ID 的 GraphQL 變量。連接 ID 可通過連接字段的__id或ConnectionHandler.getConnectionIDAPI 獲取。命令式修改 storeupdater函數(shù)當更新邏輯比寫入響應(yīng)字段更復雜且聲明式指令無法覆蓋時UseMutationConfig接受updater函數(shù)把 store 的寫入完全交給你控制。詳見 Imperatively modifying store data。什么時候用 updater復雜的客戶端更新比簡單地把網(wǎng)絡(luò)響應(yīng)寫進 store 更復雜、且聲明式指令搞不定的場景客戶端 schema 擴展字段的初始化網(wǎng)絡(luò)響應(yīng)必然不包含 client schema extensions 中定義的字段可以用 updater 為其初始化數(shù)據(jù)其他 API 無法完成的操作如失效節(jié)點、刪除節(jié)點、按字段查找所有連接等多個樂觀響應(yīng)修改同一個 store 值時若兩個樂觀響應(yīng)各把點贊數(shù) 1第一個被回滾后第二個仍生效且不會被重算點贊數(shù)會保持 2——這種疊加場景下應(yīng)使用樂觀 updater詳見下文樂觀更新。什么時候不要用 updater觸發(fā)其他副作用時應(yīng)該用onCompleted回調(diào)。onCompleted保證只被調(diào)用一次而 updater/optimistic updater 可能被多次調(diào)用。類型安全的 updaterreadUpdatableFragment與updatable現(xiàn)代推薦寫法是可更新的 fragment/query 類型安全的代理對象。以下例演示通過 schema extension 給Feedback增加is_new_comment字段并在 mutation updater 中把它置為true。首先定義 schema 擴展# Feedback.graphql extend type Feedback { is_new_comment: Boolean }然后在 mutation 的響應(yīng)中展開一個updatable片段并在updater中讀出并改寫它// CreateFeedback.js import type {Environment} from react-relay; import type { FeedbackCreateData, CreateFeedbackMutation, } from CreateFeedbackMutation.graphql; const {commitMutation, graphql} require(react-relay); function commitCreateFeedbackMutation( environment: Environment, input: FeedbackCreateData, ) { return commitMutationFeedbackCreateData(environment, { mutation: graphql mutation CreateFeedbackMutation($input: FeedbackCreateData!) { feedback_create(input: $input) { feedback { id # Step 1: 在 mutation 響應(yīng)中展開 updatable 片段 ...CreateFeedback_updatable_feedback } } } , variables: {input}, // Step 2: 定義 updater updater: (store, response) { // Step 3: 訪問并判空 feedback 對象 const feedbackRef response?.feedback_create?.feedback; if (feedbackRef null) { return; } // Step 4: 用 store.readUpdatableFragment 讀出可更新的代理對象 const {updatableData} store.readUpdatableFragment( graphql fragment CreateFeedback_updatable_feedback on Feedback updatable { is_new_comment } , feedbackRef ); // Step 5: 直接給代理對象的字段賦值 updatableData.is_new_comment true; }, }); }這段代碼的關(guān)鍵事實updater接收兩個參數(shù)RecordSourceSelectorProxystore 代理與一個可選對象——即 mutation 響應(yīng)的讀取結(jié)果。第二個參數(shù)的類型是生成文件導出的$data類型的可空版本且只包含 mutation 直接選中的字段不含 fragment 展開出來的字段該 updater 在 mutation 響應(yīng)寫入 store之后執(zhí)行readUpdatableFragment返回帶updatableData字段的代理對象對其字段賦值即記錄到 storeupdater 完成后所有受影響組件自動重渲染。替代 APIreadUpdatableQuery如果知道從根Query類型到目標記錄之間的路徑可以用readUpdatableQuery以 query 形式讀寫例如在表單提交時更新 viewer 的namecommitLocalUpdate(environment, store { const {updatableData} store.readUpdatableQuery( graphql query NameUpdaterUpdateQuery updatable { viewer { name } } , {} ); const viewer updatableData.viewer; if (viewer ! null) { viewer.name newName; } });優(yōu)先選擇readUpdatableQuery的理由手頭沒有現(xiàn)成的 fragment reference例如commitLocalUpdate調(diào)用與某個組件沒有直接關(guān)聯(lián)手頭沒有能選中目標記錄的父記錄的 fragment由于 Relay 中一個已知的類型空洞updatable fragment 不能在頂層展開想在 updatable fragment 中使用變量。目前 updatable fragment 復用 query 傳入的變量無法用 fragment 局部變量多次調(diào)用readUpdatableFragment。修改鏈接字段assignable片段readUpdatableQuery不僅能改標量字段還能重新指定記錄間的鏈接如把某個用戶設(shè)為 viewer 的best_friend。要點是引入assignable片段extend type Viewer { best_friend: User, }// 可賦值的片段只能包含單個字段 __typename graphql fragment AssignBestFriendButton_assignable_user on User assignable { __typename } ;該片段必須在賦值來源新 best friend 上和賦值目標updatable query 中 viewer 的best_friend字段下同時展開然后即可安全賦值const environment useRelayEnvironment(); const onClick () { commitLocalUpdate( environment, (store) { const {updatableData} store.readUpdatableQuery( graphql query AssignBestFriendButtonUpdatableQuery updatable { viewer { best_friend { ...AssignableBestFriendButton_assignable_user } } } , {} ); if (data.user ! null updatableData.viewer ! null) { updatableData.viewer.best_friend data.user; } } ); };關(guān)于鏈接字段賦值有一條硬性約束被賦值的鏈接字段賦值表達式的右側(cè)必須源自只讀的 fragment/query/mutation/subscription。也就是說updatableData.foo updatableData.foo是非法的若要把列表追加元素也必須先從只讀 fragment 中取出原列表再執(zhí)行viewer.best_friends existing_list.concat([newBestFriend])。從抽象類型如Node向具體/接口類型字段賦值時還需要用內(nèi)聯(lián) fragment 做類型收窄必要時配合編譯器生成的validator導出做運行時校驗。這些進階細節(jié)都在 Imperatively modifying linked fields 中。為什么需要類型安全 updaters這套 APITypesafe updaters FAQ 給出了設(shè)計動機舊式 updater API 冗長、非類型安全、容易出錯還要求開發(fā)者只為寫 updater 學一套新方法。類型安全 updaters 復用 Relay 已有的 query/fragment/類型收窄習慣用 getter/setterupdatableData.name Godzilla代替記憶各種方法賦值操作底層仍會轉(zhuǎn)成舊 API 調(diào)用但獲得了靜態(tài)類型保障。同時需要明確updatable查詢/片段的特性它們不會被真正從服務(wù)器獲取。服務(wù)端不認識 updatable query/fragment即使把 updatable fragment 展開在普通 query 里其字段也不會隨請求下發(fā)想既獲取又修改某個字段需要在普通 query/fragment和updatable query/fragment 中同時選中它由此帶來幾個后果讀取 updatable 數(shù)據(jù)時可能因 store 中缺失而為空updatable query/fragment 中不能展開普通 fragment其生成產(chǎn)物不含 query ID 與 normalization ASTnormalization AST 用于把網(wǎng)絡(luò)數(shù)據(jù)寫入 storedefer等指令在 updatable 上下文中沒有意義、被禁止。樂觀更新optimisticResponse與optimisticUpdater很多時候我們不想等服務(wù)器響應(yīng)才反饋用戶操作。比如點擊Like后希望立即展示點贊效果——在假設(shè) mutation 必然成功的前提下先把數(shù)據(jù)寫入 store這就是樂觀更新若最終失敗則回滾該樂觀更新。樂觀響應(yīng)optimisticResponse在UseMutationConfig中加入optimisticResponse字段即可。為了讓該字段獲得 Flow 類型useMutation必須傳入類型參數(shù)并且mutation 需帶raw_response_type指令mutation LikeButtonMutation($input: FeedbackLikeData!) raw_response_type { feedback_like(data: $input) { feedback { viewer_does_like like_count } } }commitMutation({ variables: {input: {id: data.__id}}, optimisticResponse: { feedback_like: { feedback: { // 雖然 id 未顯式選中編譯器已為我們補選 id: data.__id, viewer_does_like: !data.viewer_does_like, like_count: data.like_count changeToLikeCount, }, }, }, })調(diào)用commitMutation后這份數(shù)據(jù)會被立即寫入 store匹配 id 的記錄獲得新的viewer_does_like值訂閱該字段的組件立刻重渲染。當 mutation 成功或失敗時樂觀響應(yīng)會被回滾。注意上面的like_count計算依賴組件中讀取到的當前點贊數(shù)——為此需要在 fragment 中用required(action: THROW)強制讀取viewer_does_like與like_count詳見 graphql-mutations 文檔 的完整示例。樂觀響應(yīng)存在不少陷阱需謹慎使用樂觀響應(yīng)可以包含整個 query 響應(yīng)的數(shù)據(jù)包括 fragment 展開的內(nèi)容。如果開發(fā)者后續(xù)在組件 fragment 中新增了字段樂觀更新期間這些組件可能拿到不一致或部分的數(shù)據(jù)由于樂觀響應(yīng)的類型包含所有遞歸嵌套 fragment 的內(nèi)容類型可能非常龐大給 mutation 加raw_response_type會拖慢 Relay compiler。另外若樂觀響應(yīng)的新值依賴 store 當前值、且可能有多個樂觀響應(yīng)同時影響該值應(yīng)改用樂觀 updater例如兩個樂觀響應(yīng)各把點贊數(shù) 1當?shù)谝粋€被回滾時第二個仍然生效store 中的點贊數(shù)會保持 2。樂觀 updateroptimisticUpdater當樂觀數(shù)據(jù)不在 mutation 選中的字段里、或需要向連接增刪邊而聲明式指令不夠用時UseMutationConfig還支持optimisticUpdater允許在樂觀階段命令式改寫 store——與普通updater的寫法一致詳見 Imperatively updating store data。updater 系列的執(zhí)行順序無論成功失敗mutation 涉及的更新按以下順序執(zhí)行若提供了optimisticResponse其數(shù)據(jù)先寫入 store若提供了optimisticUpdaterRelay 執(zhí)行它并按結(jié)果更新 store若提供了optimisticResponse對樂觀響應(yīng)處理 mutation 中的聲明式指令若 mutation 請求成功回滾此前應(yīng)用的樂觀更新把服務(wù)器響應(yīng)寫入 store若提供updater執(zhí)行之服務(wù)器 payload 作為 store 中的一個根字段可供其讀取用服務(wù)器響應(yīng)處理聲明式指令調(diào)用onCompleted。若 mutation 請求失敗回滾此前應(yīng)用的樂觀更新調(diào)用onError。更新連接Connections增刪邊與連接標識渲染連接如評論列表時通常還需要在用戶操作后向連接增加或移除條目。由于 store 中帶connection指令的連接字段以特殊記錄保存并累積了該連接所有已獲取條目操作它們需要先取得連接記錄。完整指南見 Updating Connections實現(xiàn)位于 packages/relay-runtime/handlers/connection/。三種方式獲取連接記錄// 方式一查詢連接的 __id 字段該字段由 Relay 自動附加服務(wù)端無需暴露 const connectionID fragmentData?.comments?.__id; // 方式二由父記錄 ID 連接 key 計算連接 ID const connectionID ConnectionHandler.getConnectionID( storyID, StoryComponent_story_comments_connection, ); // 方式三由父記錄對象直接取連接記錄 const storyRecord store.get(storyID); const connectionRecord ConnectionHandler.getConnection( storyRecord, StoryComponent_story_comments_connection, );添加邊聲明式方式在 mutation/subscription 返回 edge 或 node 的字段上使用appendEdge/prependEdge/appendNode/prependNode也適用于 query并通過connections變量傳入連接 ID 數(shù)組commitMutationAppendCommentMutation(environment, { mutation: graphql mutation AppendCommentMutation( $connections: [ID!]! $input: CommentCreateInput ) { commentCreate(input: $input) { feedbackCommentEdge appendEdge(connections: $connections) { cursor node { id } } } } , variables: { input, connections: [connectionID], }, });手工方式在 updater 中先用store.getRootField(comment_create)讀取 mutation payload 根字段再用ConnectionHandler.buildConnectionEdge(store, connectionRecord, serverEdge)構(gòu)造邊最后用ConnectionHandler.insertEdgeAfter/insertEdgeBefore插入這兩個 API 會原地修改連接。若要從零創(chuàng)建邊則用store.create創(chuàng)建本地記錄 ConnectionHandler.createEdge(store, connectionRecord, newCommentRecord, CommentEdge)。刪除邊聲明式在返回被刪節(jié)點 IDID或[ID]的字段上加deleteEdge(connections: $connections)手工ConnectionHandler.deleteNode(connectionRecord, commentIDToDelete)它會根據(jù)節(jié)點 ID 找到對應(yīng)邊并移除。無論用哪種方式修改連接渲染該連接的所有 fragment/query 組件都會收到通知并以最新連接狀態(tài)重渲染。帶過濾條件的連接標識如果連接字段帶過濾參數(shù)如order_by、filter_mode、language這些過濾值會參與連接標識——分頁參數(shù)first/last/before/after除外。也就是說過濾值的每種組合都會生成不同的連接記錄。此時ConnectionHandler.getConnection需要傳入第三個參數(shù)ConnectionHandler.getConnection( storyRecord, StoryComponent_story_comments_connection, {order_by: *DATE_ADDED*, filter_mode: null, language: null} );當過濾組合多到難以管理時可以在connection中顯式指定參與標識的filters數(shù)組comments( order_by: $orderBy filter_mode: $filterMode language: $language ) connection( key: StoryComponent_story_comments_connection filters: [order_by, filter_mode] ) { edges { nodes { body { text } } } }這樣只有order_by與filter_mode影響連接身份language變化不會產(chǎn)生新連接記錄——前提是它確實不改變服務(wù)端返回的條目集合或排序或該參數(shù)在應(yīng)用中永不變化。純本地數(shù)據(jù)更新commitLocalUpdate與commitPayload有些更新完全不涉及服務(wù)端操作。Relay 為此提供了兩個 API詳見 Local Data Updates它們既可以作用于客戶端專屬數(shù)據(jù)也可以作用于從服務(wù)端取回的普通數(shù)據(jù)。commitLocalUpdate接受一個 environment 與一個 updater 函數(shù)const {commitLocalUpdate, graphql} require(react-relay); function commitCommentCreateLocally( environment: Environment, feedbackID: string, ) { return commitLocalUpdate(environment, store { // 在這里命令式地修改 store }); }updater 的store參數(shù)是RecordSourceSelectorProxy實例完整 API 見 api-reference/store可以命令式讀寫 store創(chuàng)建全新記錄、更新或刪除既有記錄與 mutation/subscription 的 updater 不同commitLocalUpdate的 updater不接受第二個參數(shù)——因為它沒有關(guān)聯(lián)的網(wǎng)絡(luò)響應(yīng)本地更新會自動通知訂閱了相關(guān)數(shù)據(jù)的組件并觸發(fā)重渲染。commitPayload接受一個OperationDescriptor與 query 的 payload將其寫入 store。payload 會像普通 query 的網(wǎng)絡(luò)響應(yīng)一樣被歸一化處理也會解析以JSResource、requireDefer等傳入的 Data Driven Dependenciesimport type {FooQueryRawResponse} from FooQuery.graphql const {createOperationDescriptor} require(relay-runtime); const operationDescriptor createOperationDescriptor(FooQuery, { id: an-id, otherVariable: value, }); const payload: FooQueryRawResponse {...}; environment.commitPayload(operationDescriptor, payload);OperationDescriptor由createOperationDescriptor(query, variables)創(chuàng)建payload 的類型來自給 query 加raw_response_type指令后生成的 Flow 類型同樣地任何本地更新都會自動通知訂閱組件并觸發(fā)重渲染??蛻舳藢贁?shù)據(jù)Client Schema ExtensionsRelay 允許在瀏覽器端擴展 GraphQL schema用來建模只在客戶端創(chuàng)建/讀取/更新的數(shù)據(jù)——例如給服務(wù)端取回的數(shù)據(jù)附加小塊本地信息或完整建模一段客戶端專屬狀態(tài)。詳見 Client-only data。擴展既有類型extend type Comment { is_new_comment: Boolean }新增客戶端專屬類型同一文件可定義多個類型且可引用服務(wù)端類型enum FetchStatus { FETCHED PENDING ERRORED } type FetchState { status: FetchStatus started_by: User! } extend type Item { fetch_state: FetchState }讀取客戶端專屬數(shù)據(jù)與讀取普通字段完全一致在 fragment/query 中直接選中更新它們則可以在 mutation/subscription 的 updater 中完成或使用上文介紹的本地更新原語commitLocalUpdate/commitPayload。GraphQL Subscriptions訂閱服務(wù)端事件流除了 mutation 這種客戶端主動發(fā)起的寫入Relay 還支持通過GraphQL subscriptions響應(yīng)服務(wù)端事件流。完整指南見 GraphQL subscriptions。聲明訂閱訂閱與 query 類似只是使用subscription關(guān)鍵字subscription FeedbackLikeSubscription($input: FeedbackLikeSubscribeData!) { feedback_like_subscribe(data: $input) { feedback { like_count } } }feedback_like_subscribe是subscription 根字段負責在后臺建立訂閱與 mutation 類似訂閱分兩步處理先發(fā)生服務(wù)端事件再執(zhí)行查詢注意事件流可以與所選字段完全無關(guān)——不保證每次通知所選值都發(fā)生了變化。使用useSubscriptionconst {graphql, useSubscription} require(react-relay); const {useMemo} require(React); function useFeedbackSubscription(input: FeedbackLikeSubscribeData) { const config useMemo(() ({ subscription: graphql subscription FeedbackLikeSubscription($input: FeedbackLikeSubscribeData!) { feedback_like_subscribe(data: $input) { feedback { like_count } } } , variables: {input}, }), [input]); return useSubscription(config); }要點useSubscription接受一個GraphQLSubscriptionConfig對象包含subscription訂閱字面量與variables建立訂閱所用的變量同樣建議傳入 Flow 類型參數(shù)以獲得靜態(tài)類型與useLazyLoadQuery不同Relay 不會在渲染階段建立訂閱訂閱在 hook 提交后建立每次事件到達Relay 按id匹配 store 中的記錄并更新相關(guān)組件自動重渲染。?? 傳給useSubscription的GraphQLSubscriptionConfig必須被 memoized如上例用useMemo否則useSubscription會在每次渲染時銷毀并重建訂閱GraphQLSubscriptionConfig還支持回調(diào)字段onNext收到 payload 時、onError出錯時、onCompleted服務(wù)端結(jié)束訂閱時。聲明式指令deleteRecord、連接增刪指令同樣適用于訂閱。訂閱需要網(wǎng)絡(luò)層支持通常在 network-layer 指南 中配置 WebSocket 傳輸如graphql-ws并把subscribe函數(shù)通過Network.create(fetchQuery, subscribe)注入。在 mutation 期間失效數(shù)據(jù)Staleness執(zhí)行 mutation 的推薦做法是在 mutation 體內(nèi)把受影響的數(shù)據(jù)全部請求回來讓本地 store 與服務(wù)端保持一致。但某些漣漪效應(yīng)巨大的 mutation如屏蔽用戶退出群組很難枚舉全部受影響數(shù)據(jù)。此時更直接的做法是顯式標記部分數(shù)據(jù)或整個 store為過期讓 Relay 在下次渲染時自動 refetch。相關(guān) API 見 Staleness of Data 章節(jié)。小結(jié)Relay 的數(shù)據(jù)更新體系圍繞本地 store 與服務(wù)端保持一致這一核心目標設(shè)計形成了一條清晰的能力階梯簡單場景優(yōu)先用聲明式手段——mutation 響應(yīng)自動歸一化寫入 store、deleteRecord刪除記錄、appendEdge等指令操作連接中等場景用updater/optimisticResponse在響應(yīng)寫入前后微調(diào) store控制執(zhí)行時機與回滾語義復雜場景用類型安全的readUpdatableQuery/readUpdatableFragmentupdatable與assignable片段精確改寫標量字段與鏈接關(guān)系純本地狀態(tài)用commitLocalUpdate/commitPayload與 client schema extensions 建??蛻舳藢贁?shù)據(jù)服務(wù)端推送用useSubscription訂閱事件流配合 WebSocket 網(wǎng)絡(luò)層。無論走哪條路徑最終效果都是一致的store 中的記錄被更新訂閱了相關(guān)字段的組件自動重渲染——這正是 Relay局部寫、全局一致的數(shù)據(jù)驅(qū)動哲學在寫入側(cè)的體現(xiàn)。若要繼續(xù)深入推薦按順序閱讀 GraphQL mutations、命令式修改 store 數(shù)據(jù) 與 更新連接 三篇文檔并結(jié)合 useMutation 源碼 與 ConnectionHandler 實現(xiàn) 理解底層行為。贊分享前端開發(fā)工具【免費下載鏈接】relayRelay is a JavaScript framework for building>項目地址https://gitcode.com/gh_mirrors/relay29/relay點擊查看免費下載相關(guān)推薦Relay GraphQL Mutations 完全指南從 useMutation 到樂觀更新與 Store 數(shù)據(jù)同步Relay GraphQL Mutations 完全指南從 useMutation 到樂觀更新與 Store 數(shù)據(jù)同步 本指南基于倉庫中的官方文檔 graph前端開發(fā)工具Relay 數(shù)據(jù)更新指南Mutation、Subscription 與本地 Store 命令式修改Relay 數(shù)據(jù)更新指南Mutation、Subscription 與本地 Store 命令式修改 本篇技術(shù)指南以 RelayRelay is a Java前端開發(fā)工具Relay 18 類型安全 Store 更新指南使用 readUpdatableQuery / readUpdatableFragment 命令式修改 Store 數(shù)據(jù)Relay 18 類型安全 Store 更新指南使用 readUpdatableQuery / readUpdatableFragment 命令式修改 Sto前端開發(fā)工具創(chuàng)作聲明:本文部分內(nèi)容由AI輔助生成(AIGC),僅供參考