【问题标题】:How do you catch incorrect location pathnames in React Router when using the <Router> component?使用 <Router> 组件时,如何在 React Router 中捕获不正确的位置路径名?
【发布时间】: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


【解决方案1】:

尝试使用* 路径添加路由。

const rootRoute = {
    childRoutes: [ {
        path: '/',
        component: require( './components/Layout' ),
        childRoutes: [
            require('./routes/HelloBeautiful'),
            require('./routes/GreetingsEarthlings'), ... (etc.)
        ]
    }, 
    ...
    {
        path: '*',
        component: require( './components/NotFoundPage' ),
    }]
}

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 2018-11-03
    • 1970-01-01
    • 2017-03-25
    • 2020-06-06
    • 1970-01-01
    • 2019-07-02
    • 2016-09-28
    • 2019-11-19
    相关资源
    最近更新 更多