簡體   English   中英

React / Redux處理雙向數據

[英]React/Redux Handling Two-Way Data

我正在努力正確地組織我的Redux Store和我的React組件以正確處理雙向嵌套數據。

假設我有一個post模型和一個user模型。 讓我們舉一個抽象的例子:

const user = {
    "id": "1",
    "name": "user 1",
    "posts": [...] // list of post objects
}

const post = {
    "id": "1",
    "title": "post 1",
    "user": user
}

問題是我無法像這樣加載此數據,因為它將導致無限遞歸錯誤。 我必須忽略userposts或忽略userposts

這是我理想中需要的:

我需要有一個post頁面顯示后user與所有他的信息(ID,姓名)和用戶的列表posts與職位信息(ID,標題)在同一個屏幕上同時。

我使用normalizr標准化數據。

我將如何加載數據?

根據Redux文檔( https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape ),您應該避免嵌套對象。

這里的解決方案是像對待數據庫一樣對待數據。 這意味着您應該存儲ID而不是對象。

在您的示例中:

const user = {
  "id": "1",
  "name": "user 1",
  "posts": ["1", "2", ...] // list of post objects IDs
}

const post = {
  "id": "1",
  "title": "post 1",
  "userId": "1"
}

通常,您只將post_ids保存在用戶中,將user_id保存在帖子中。 可以將normalizer模式配置為處理那些關系。

post中添加user密鑰的動機是什么? 在兩個相關的數據結構中共享數據是多余的。 你應該有唯一的數據post的相關數據,您需要正確的關聯信息的最小量user與他/她的post秒。 我想您會希望在post中使用用戶的字符串名稱,或者在每個post對象中使用用戶的ID號

const user = {
    "id": "1",
    "name": "user 1",
    "posts": [...] // list of post objects
}

const post = {
    "id": "1",
    "title": "post 1",
    "user": "user 1"
}

編輯:從您的評論,我將使所有users的數組。 但是, post鍵只是與該用戶關聯的帖子的ids 還有另一組只有posts 和以前一樣,具有將兩者關聯的標識符。 之后,根據需要解析前端。

const users = [
  { name: 'andrew', id: 10, postIds: [1,3,23,30]},
  // ...more users
]

const posts = [
  { name: 'a post', id: 23, userId: 10 }
  { name: 'another post', id: 3, userId: 10 }
  { name: 'a third post', id: 2, userId: 3 }
  // ...more posts
]

從技術上講, userId是可選的,但在檢查單個帖子時能夠識別用戶可能是一個很好的選擇

編輯:哇,我只是向下滾動,看到諾德在我之前有完全一樣的提議。 很高興看到我們在同一頁面上,但是,如果您喜歡這個主意,請確保他/她得到好評;)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM