如何使用 react-router v4 重定向到绝对路径?

How can I redirect to an absolute path with react-router v4?

我有一个巨大的 Django 网络应用程序,其中一个模块('dashboard')是用节点和 React 编写的。用户登录由 Django 模块处理。

用户应该登录到主应用程序才能访问 React 仪表板,这部分工作 - 代码从浏览器获取用户会话,并且仅在存在时呈现内容。

如果没有会话,我现在想将用户重定向到主应用程序登录页面,但我不知道如何使用我当前的结构(以及这个该死的 v4 路由器)。

我在 BrowserRouter 组件中使用一个基本名称来使用相对于 Django 应用程序中的仪表板路径的路由。

这是我为 app.jsx 的 JSX 想出的:

<BrowserRouter basename='/en/dashboard'>
    {this.state.isAuthenticated ? (
        <Paper zDepth={0} style={{ height: '100%', backgroundColor: grey900 }}>
            <div style={{height: '100%'}}>
                <Header />
                <Switch>
                    <Route exact={true} path='/' component={FirstSection}/>
                    <Route path='/first' component={FirstSection}/>
                    <Route path='/second' component={SecondSection}/>
                </Switch>
            </div>
        </Paper>
    ) : (
        <Redirect to="/en/login"/>
    )}
</BrowserRouter>

然而,它实际上重定向到 en/dashboard/en/login。我相信我可以从 BrowserRouter 中删除 'basename' 属性 并将其添加到每个后续 Route 中,但是如果这个模块最终变大,它会使路由更难。有更好的方法吗?

很遗憾,这是不可能的。如果您使用的是基名,它将在创建 href 之前添加到每个路径的基中。这发生在 createBrowserHistorypushreplace 方法中的 history 模块中,这些方法使用以下函数:

var createHref = function createHref(location) {
    return basename + (0, _PathUtils.createPath)(location);
};

使用 pushreplace 方法。

您可以在Redirect.prototype.perform方法中找到以下代码块:

if (push) {
  history.push(to);
} else {
  history.replace(to);
}

以上可以在 react-router 模块中的 Redirect.js 中找到,这是 react-router-dom 模块导入然后导出的内容。

为了完成您想要做的事情,我会将 basename 设为常量并将其添加到您的每条路线中路径的前面。

遗憾的是 <Route /><Redirect /> 没有 ignoreBasename 选项,尽管它是可以实现的。

正如 Kyle 的回答中提到的,没有办法必须使用绝对 url 或忽略基本名称;但是,如果您想要或 "need" 到 运行 从组件的渲染方法重定向,您可以创建自己的超轻型 "absolute redirect" 组件,这是我的:

import React from 'react'

class AbsoluteRedirect extends React.Component {

    constructor(props){
        super(props)
    }

    componentDidMount(){
        window.location = this.props.to
    }

    render(){
        return null
    }

}

export default AbsoluteRedirect

然后将它与其他组件一起使用,这样只有当您的验证为真时,它才会被挂载。

render(){ 

    if( shouldRedirect )
        return <AbsoluteRedirect to={ anotherWebsiteURL } />

    ...

}

希望这对您有所帮助:)

不用react router也可以做到:

window.location.pathname = '/en/login';

导航到另一个站点正在使用:

window.location.href = 'https://whosebug.com';