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脫落基地:)
我試過這個,它對我來說真的有意義,它會像你所描述的那樣工作。但是,當我嘗試console.log()initialAction中的新的url參數,我仍然無法訪問參數。我用我的路線更新了我的問題。從我匹配的路線判斷,我應該有一個'category'參數可用。 任何想法,爲什麼我可能不? – Gurnzbot
當你在initialAction裏面做console.log(道具)時打印什麼? –
它應該打印的網址。如果是這樣,你可以從那裏提取參數。 –