2017-10-20 121 views
3

我正在使用react-router v4來生成從異步API中加載的動態路由。從API檢索到的數據通過其將創建陣營路由函數通過,類似於:在Redux中存儲React路由

import Home from "containers/home" 
import FeaturePage from "containers/featurePage" 

response.map((item) => { 
    if (item.value.toLowerCase() === "home") { 
    return { 
     path: item.path, 
     component: Home, 
     exact: item.isExact 
    } 
    } else if (item.value.toLowerCase() === "featurePage") { 
    return { 
     path: item.path, 
     component: FeaturePage, 
     exact: item.isExact 
    } 
    } else { 
     // ...etc 
    } 
}); 

一旦路由被加載,它們被使用動作減速器照常加入到Redux的存儲。這在redux商店支持功能時效果很好。

但是在Redux商店doesn't seem to be the best way forward中存儲函數。什麼是更好的實施?我需要存儲需要渲染的組件,這是不可序列化的。

回答

1

只需將組件名稱存儲爲字符串? (不知道爲什麼你想將它們添加到店雖然)

你或許可以在以後使用它們像這樣:

import Home from "containers/home" 
import FeaturePage from "containers/featurePage" 

// Assume the routes have been added to the redux store 
const Routes = { 
    Home, 
    FeaturePage 
}; 

response.map(({ component, path, exact }) => { 
    return (
    <Route 
     key={ path } 
     exact={ exact } 
     path={ path } 
     component={ Routes[component] } 
    /> 
); 
}); 
+0

我設法通過在存儲中存儲組件名稱然後將組件名稱傳遞給返回組件的函數來實現此目的。我需要這個組件,以便在創建react-router組件時引用它。來自 「容器/家」 常量getRouteComponent =名=> { 開關(名稱){ 情況下 「主頁」 ''' 導入主頁: 返回首頁; 默認值: return undefined; } }; ''' –

+2

如果你能夠更新你的例子,我可以把它標記爲正確的。 我創建'使用反應-router'路線: {routes.map(路線=> { 回報( <路線 關鍵= {} route.path確切 路徑 = {route.path} 部件= {getRouteComponent(route.component)} /> ); }}} –

0

一個陣營組件由組件的狀態(由的stateprops)以及基於狀態修改的一些行爲(如函數和html標記)。一旦創建了組件,組件的行爲將不會改變;只有組件的狀態會改變。

我認爲保存組件的狀態足以在稍後重新創建組件,並且不需要將組件保存在Redux中;而是在Redux中保存組件的狀態。

關於在Redux中保存路由,同樣適用;你應該保存路線的狀態,而不是你的Redux商店中的路線本身。你可以有一個函數可以接受這個狀態對象(包含路徑,isExact,組件名等)並將其轉換爲一個真實的組件。

希望這會有所幫助!

相關問題