1
1
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:
Brent Jackson 2018-05-28 12:24:27 -04:00 committed by GitHub
commit e8dae1057a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 8 deletions

37
docs/dynamic.js Normal file
View 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>
}
}

View File

@ -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 }
}