reactjs - 在没有反应路由器的情况下以编程方式重定向到 URL

标签 reactjs redirect redux

我在没有第 3 方路由器帮助的情况下运行 SPA。我想在函数内重定向到外部 URL。

显然 href 和安装路由器不能解决我的问题。

最佳答案

如果你想重定向到外部 URL 而不是内部的东西,那就更容易了。你掌握了 window.location对象,你可以让它成为可能。我能理解为什么 <a href>以编程方式执行此操作不是正确的选择。

下面的工作非常好。我用了 setTimeout模拟编程重定向。

class App extends React.Component {
  componentDidMount() {
    setTimeout(() => {
      window.location.href = 'https://praveen.science/';
    }, 1000);
  }
  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

关于reactjs - 在没有反应路由器的情况下以编程方式重定向到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56058856/

相关文章:

javascript - React Alert 组件关闭按钮自关闭

reactjs - React keycloak 集成不会重定向到登录页面

Android - 如何检测来电是否被重定向?

java - 如何使用 Java HTTPS 服务器管理 HTTP 请求?

javascript - redux-saga:函数被调用两次

node.js - 部署到 heroku 的 React/Node 应用程序显示空白屏幕

reactjs - 如何导航到外部 URL?

javascript - 即使页面重定向回来后如何保留表单值

reactjs - Redux - 错误 : Invalid value of type object for mergeProps

Reactjs,this.context 已弃用