2017-02-13 50 views
2

我將React集成到現有的應用程序中。這個應用程序是數據密集型的,數據結構非常複雜,這使我很難適應React模式,尤其是無狀態和組合。具有複雜數據結構的ReactJS最佳實踐

這樣的假設數據:

component: { 
 
    options: [optionA, optionB, optionC] 
 
} 
 

 
options: { 
 
    optionA : { 
 
    name: 'FOO', 
 
    choices: [choiceA, choiceB, choiceC] 
 
    }, 
 
    optionB : { 
 
    name: 'BAR', 
 
    choices: [choiceD, choiceE] 
 
    }, 
 
    ... 
 
} 
 

 
choices: { 
 
    choiceA : { 
 
    type: 'typeA', 
 
    choices: [choiceA, choiceB, choiceC], 
 
    name: 'abb' 
 
    }, 
 
    choiceB : { 
 
    type: 'typeB', 
 
    name: 'abc' 
 
    }, 
 
    ... 
 
}

由於該數據是由IDS鏈接我有兩個可能性:

  1. 檢索兒童的數據在父組件,並將其傳遞給孩子們。

  2. 通過身份證和子女檢索自己的數據。

意味着一個動態檢索組件道具和其他意味着具有擁有所有必要的數據,這是孩子們的「上帝」的父母,哪一個纔是更好的方法?

我的另一個問題是,如果選擇Choice作爲其道具的組件應該根據它的選擇類型顯示不同,是製作像這樣的包裝組件的更好方法嗎? :

class Choice extends Component { 
 
    constructor(props){ 
 
    super(props); 
 
    } 
 
    
 
    render(){ 
 
    switch(props.choice.type){ 
 
     case "typeA": 
 
     return (<TypeAComponent />); 
 
     case "typeB": 
 
     return (<TypeBComponent />); 
 
     default: 
 
      return (..); 
 
    } 
 
    } 
 
}

或者是有一個更清潔的替代(我有點過敏切換的情況下)...

回答

3

廣告你的第一個問題:

我會選擇第一個解決方案,即檢索父數據。如果你選擇這麼容易(這將只在一個地方處理),這將轉移到某種狀態管理(redux)。

廣告你的第二個問題:

您可以使用字典擺脫開關:

const choiceRenderers = { 
    "typeA":() => <TypeAComponent />, 
    "typeB":() => <TypeBComponent />, 
    // etc. 
}; 

class Choice extends Component { 
    render() { 
     const renderer = choiceRenderers[this.props.choice.type]; 
     return renderer 
      ? renderer() 
      : <DefaultChoice />; 
    } 
} 

的潛在優勢是,這種選擇分量映射可以跨多個組件共享,不復制它,您可以將其存儲在模塊中並在需要時導入它。

+0

謝謝,這證實了我的想法! 關於遷移到Redux,你認爲它適用於深度鏈接的數據結構嗎? –

+1

根據redux的創建者Dan Dan Abramov(http://stackoverflow.com/users/458193/dan-abramov),它對淺層狀態樹更好。欲瞭解更多信息,我不能推薦他的[egghead當然](https://egghead.io/lessons/javascript-redux-normalizing-the-state-shape),這是一個很好的學習資源 –