【问题标题】:Redirect with React Router使用 React 路由器重定向
【发布时间】:2019-07-16 03:30:41
【问题描述】:

我正在使用 Nodejs 后端为 OAuth 返回一个自定义重定向 URL。我试图让 React 将用户重定向到这个 URL,但是它将 localhost 添加到它的前面。

import React, { Component } from "react";
import { withRouter } from "react-router";
import axios from "axios";

class Test extends Component {

async componentDidMount() {
const profileData = await axios.get("/connect");
this.props.history.push(profileData.data);
}

render() {
return <div />;
}
}

export default withRouter(Test);

假设 profileData.data 返回的字符串是http://www.google.com,网页被重定向到http://localhost:3000/http://www.google.com

有没有办法使用 React 进行重定向,使其重定向到特定的 URL,而不是尝试重定向到子页面?

【问题讨论】:

  • 只有在您留在自己的网站上时,React 路由器才能为您提供帮助。只是一个window.location.href = profileData.data 怎么样?

标签: javascript node.js reactjs redirect react-router


【解决方案1】:

只需在您的 componentDidMount 函数中设置位置 href。我会这样写:

componentDidMount() {
  axios.get("/connect")
    .then((response) => {
      window.location.href = response.data
    })
}

【讨论】:

    猜你喜欢
    • 2021-04-27
    • 2020-11-25
    • 2018-10-14
    • 2018-12-29
    • 2019-06-25
    • 2023-02-03
    • 2021-02-04
    • 2016-09-01
    • 1970-01-01
    相关资源
    最近更新 更多