首页 > 解决方案 > 如何使用相对 URL 进行重定向?

问题描述

我正在尝试从我的页面上的下拉列表中重定向注销按钮。当我现在点击退出时,它将转到 localhost:3000/signout。我努力了:

export const SIGNOUT="redirect=www.google.com";

它会简单地将 URL 替换为 localhost:3000/redirect=www.google.com。

我努力了 :

<Route exact path={SIGNOUT}>
    <Redirect to={www.google.com}/>
</Route>
export const SIGNOUT="www.google.com";

这将在加载时重定向到 google.com,甚至不会让我加载自己的网页:

export const SIGNOUT= window.location.replace("http://www.google.com");

urlLists.js

export const SIGNOUT= "www.google.com";

应用程序.js

import {SIGNOUT} from "./utils/urlLists";

class App extends Component {
    render() {
        const {location} = this.props
        return (
            <Switch>
                <Route exact path={SIGNOUT}>
                    <Redirect to={HOME}/>
                </Route>
            </Switch>
        );
    }
}

export default withRouter(App);

我希望单击“退出”下拉选项后,结果会重定向到 Google。

实际结果是重定向到:

localhost:3000/www.google.com

或者 Google 页面已加载,而我的 localhost:3000 没有。

标签: javascriptreactjsreact-router-dom

解决方案


这个想法是在你的组件内部重定向。Home看看这个示例实现。

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function Home() {
  return (
    <div className="App">
      <h1>Hello World</h1>
      <button
        name="sign-out"
        onClick={() => {
          // sign user out here
          window.location.assign("www.google.com");
        }}
      >
        Sign Out
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Home />, rootElement);

Redirect组件非常适合重定向到内部路由。但是,如果您要将用户踢出您的应用程序,您应该使用其他类似window.location.assign().


推荐阅读