2017-09-08 29 views
0

我正試圖渲染一個動態路由,預加載了通過異步thunk獲取的數據。如何在預加載服務器端渲染時訪問動態路由參數

我的組件中有一個靜態的initialAction方法需要預加載,並讓他們根據需要調用操作。一旦所有操作完成並且承諾解決,我將呈現路由/頁面。

我的問題是:如何在靜態函數內引用路徑參數和/或道具?

以下是將調用可能需要預加載數據的任何initialAction函數的相關代碼。

const promises = routes.reduce((promise, route) => { 
    if (matchPath(req.url, route) && route.component && route.component.initialAction) { 
     promise.push(Promise.resolve(store.dispatch(route.component.initialAction(store)))) 
    } 
    return promise; 
}, []); 

Promise.all(promises) 
.then(() => { 
    // Do stuff, render, etc 
}) 

在我的部分,我有靜態initialAction功能,將採取在商店(從服務器)和道具(從客戶端)。不管怎樣,這個類別都應該通過redux/thunk獲取。正如你所看到的,當我通過服務器加載時,我沒有通過動態permalink道具,因爲我無法檢索它。

class Category extends Component { 

    static initialAction(store, props) { 
     let res = store !== null ? getCategory(REACT_APP_SITE_KEY) : props.getCategory(REACT_APP_SITE_KEY, props.match.params.permalink) 
     return res 
    } 

    componentDidMount(){ 
     if(isEmpty(this.props.category.categories)){ 
      Category.initialAction(null, this.props) 
     } 
    } 

    /* ... render, etc */ 
} 

最後,這裏是我使用的路線:

import Home from '../components/home/Home' 
import Category from '../components/Category' 
import Product from '../components/product/Product' 
import NotFound from '../components/NotFound' 

export default [ 
    { 
     path: "/", 
     exact: true, 
     component: Home 
    }, 
    { 
     path: "/category/:permalink", 
     component: Category 
    }, 
    { 
     path: "/:category/product/:permalink", 
     component: Product 
    }, 
    { 
     component: NotFound 
    } 
] 

不能完全確定,我甚至這樣一個「標準」的方式,但這個過程的工作從而對遠時非動態路線。但是,我有一種感覺,我waaaay脫落基地:)

回答

1

在服務器上你有請求對象和在客戶端上,你有位置對象。檢查當前環境後,從這些對象中提取URL參數。

const promises = routes.reduce((promise, route) => { 
    var props = matchPath(req.url, route); 
    if (obj && route.component && route.component.initialAction) { 
     promise.push(Promise.resolve(store.dispatch(route.component.initialAction(store, props)))) 
    } 
    return promise; 
}, []); 

現在您將在initialAction的桌面和服務器中獲得url。你可以從這個提取動態路由參數

+0

我試過這個,它對我來說真的有意義,它會像你所描述的那樣工作。但是,當我嘗試console.log()initialAction中的新的url參數,我仍然無法訪問參數。我用我的路線更新了我的問題。從我匹配的路線判斷,我應該有一個'category'參數可用。 任何想法,爲什麼我可能不? – Gurnzbot

+0

當你在initialAction裏面做console.log(道具)時打印什麼? –

+0

它應該打印的網址。如果是這樣,你可以從那裏提取參數。 –

相關問題