2017-04-22 77 views
2

這是我的routes.js,我有一個問題,將已在userProfiles中收到的數據傳遞給該用戶的userProfileDetail。我不想再做另一API調用userProfileDetail,因爲已經有在userProfiles使用反應路由器將對象傳遞到反應組件

const routes = { 
    component: Base, 
    childRoutes: [ 
    { 
     path: '/profiles', 
     getComponent: (location, callback) => { 
     callback(null, userProfiles); 
     } 
    }, 

    { 
     path: '/profile/:profile_id', 
     getComponent: (location, callback) => { 
     callback(null, userProfileDetail); 
     } 
    } 
    ] 
}; 

如何導航呼叫只是通過

<Link to={ /profile/${user._id} } />userProfiles,但如何通過userProfilesuserProfileDetail

回答

1

您必須撥打另一個電話

如果什麼人刷新上userProfileDetail的頁面?如何獲取任何數據?你不能對用戶已有的數據做出假設。您必須確保任何頁面都可以自行構建。

使用狀態管理

一個偉大的方式在你的應用程序是實現狀態管理系統,如redux這樣你可以調用您的應用程序進行數據傳遞這樣多餘的,你從任何組件有任何數據共享數據。

0

您可以使用react-router的state

設置一個對象到to道具在你的鏈接中是這樣的。

<Link to={{ 
    pathname: `/profile/${user._id}`, 
    state: { userProfiles: userProfiles } 
}}/> 

現在您可以從location訪問此狀態。

location.state.userProfiles 

另外請注意,state不會有任何價值,如果用戶在瀏覽器中直接鍵入網址導航頁面或重新加載頁面。因此,理想的解決方案是調用API並使用user._id加載這些數據,如果state沒有價值。