【发布时间】:2017-08-01 06:52:59
【问题描述】:
假设你使用 react-router 以这种方式构建你的 react 应用程序:
const rootRoute = {
childRoutes: [ {
path: '/',
component: require( './components/Layout' ),
childRoutes: [
require('./routes/HelloBeautiful'),
require('./routes/GreetingsEarthlings'), ... (etc.)
]
}]
}
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}
routes={rootRoute}>
</Router>
</Provider>,
document.getElementById( 'root' )
);
如果用户尝试转到 rootRoute 常量的 childRoutes 中未指定的路由之一,您希望将用户重定向到 HelloBeautiful 路由。
您可以在 Layout.js 中的 componentWillReceiveProps 或 componentDidUpdate 内部实现检查,以将位置道具与子路由的主列表进行比较,但这似乎很乏味。
你是做什么的?我发现的其他相关问题是使用组件解决不同的 react-router 样式。
编辑:
像这样实现@stkvtflw 的答案:
Layout.js渲染:
render() {
return (
<div>
{this.props.children || <Welcome/>}
</div>
)
}
index.jsrootRoute
const rootRoute = {
childRoutes: [ {
path: '/',
component: require( './components/Layout' ),
childRoutes: [
require('./routes/HelloBeautiful'),
require('./routes/GreetingsEarthlings'), //... (etc.)
{ path: '*' } // don't need to require a component here
]
}]
}
Welcome.jscomponentDidMount:
componentDidMount() {
browserHistory.push('/hellobeautiful')
}
不需要创建 PageNotFound 组件,因为所需的行为只是在断开的链接上重定向。
【问题讨论】:
-
用
path: '*'创建最后一个子路由。它应该有帮助 -
@stkvtflw 究竟如何?
标签: reactjs react-router