mirror of
https://github.com/c8r/x0.git
synced 2024-08-16 17:00:24 +03:00
Merge pull request #58 from c8r/initial-props-path
Basic support for getInitialProps for dynamic routes
This commit is contained in:
commit
e8dae1057a
37
docs/dynamic.js
Normal file
37
docs/dynamic.js
Normal file
@ -0,0 +1,37 @@
|
||||
import React from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
const routes = [
|
||||
{ path: '/dynamic' },
|
||||
{ path: '/dynamic/hello' },
|
||||
{ path: '/dynamic/hi' },
|
||||
]
|
||||
|
||||
export default class extends React.Component {
|
||||
static getInitialProps = async ({ path }) => {
|
||||
let title = 'dynamic'
|
||||
switch (path) {
|
||||
case '/dynamic/hello':
|
||||
title = 'hello'
|
||||
break
|
||||
case '/dynamic/hi':
|
||||
title = 'hi'
|
||||
break
|
||||
}
|
||||
return {
|
||||
routes,
|
||||
path: '/dynamic/:id*',
|
||||
title,
|
||||
}
|
||||
}
|
||||
|
||||
render () {
|
||||
return <div>
|
||||
<pre>dynamic routing</pre>
|
||||
<Link to='/'>Home</Link>
|
||||
<Link to='/dynamic'>Dynamic Routes</Link>
|
||||
<Link to='/dynamic/hello'>Hello</Link>
|
||||
<Link to='/dynamic/hi'>Hi</Link>
|
||||
</div>
|
||||
}
|
||||
}
|
29
lib/build.js
29
lib/build.js
@ -125,16 +125,29 @@ const getRoutes = async (App) => {
|
||||
const routes = await App.getRoutes()
|
||||
|
||||
const dynamicRoutes = []
|
||||
routes.forEach(route => {
|
||||
if (route.props.routes) {
|
||||
route.props.routes.forEach(subroute => dynamicRoutes.push(
|
||||
Object.assign({}, route, subroute)
|
||||
))
|
||||
}
|
||||
})
|
||||
await Promise.all(
|
||||
routes.map(async route => {
|
||||
if (!route.props.routes) return null
|
||||
await Promise.all(
|
||||
route.props.routes.map(async subroute => {
|
||||
const pageProps = typeof route.Component.getInitialProps === 'function'
|
||||
? await route.Component.getInitialProps(subroute)
|
||||
: {}
|
||||
dynamicRoutes.push(
|
||||
Object.assign({}, route, subroute, {
|
||||
props: Object.assign({}, route.props, subroute.props, pageProps)
|
||||
})
|
||||
)
|
||||
return
|
||||
})
|
||||
)
|
||||
return
|
||||
})
|
||||
)
|
||||
|
||||
const staticRoutes = [
|
||||
...routes.filter(route => !route.props.routes),
|
||||
...dynamicRoutes
|
||||
...dynamicRoutes.filter(route => !!route)
|
||||
]
|
||||
return { routes, staticRoutes }
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user