React中的重定向不起作用

问题描述 投票:1回答:1

我想知道为什么,在5秒之后,它会重定向到空白页面而不是我想要的页面。我已经调用了函数作为回报,但我猜它并没有真正起作用。有人能帮我吗?

import React from 'react'
import styled from 'react-emotion'
import { Redirect } from 'react-router-dom'

class ErrorPage extends React.Component {
  state = {
    redirect: false
  }

  componentDidMount() {
    this.timeoutHandle = setTimeout(() => {
      this.setState({
        redirect: true
      })
    }, 5000)
  }

  renderRedirect = () => {
    if (this.state.redirect === true) {
      return <Redirect to="https://www.google.com/" />
    }
  }

  render() {
    return (
      <ErrorContainer>
        {this.renderRedirect()}
        <ErrorText>Page Not Found</ErrorText>
        <ErrorBox>
          <ErrorDesc>We are sorry, but the page you are looking for does not exist</ErrorDesc>
        </ErrorBox>
      </ErrorContainer>
    )
  }
}
export default ErrorPage
reactjs redirect
1个回答
0
投票

如果使用React Router组件,则必须使用路由器将理解的路由重定向,这意味着所有路由必须位于同一个应用程序中,并且不能是外部链接。如果您使用外部链接重定向,该链接将添加到您的网址,如:

http://localhost:1234/https://www.google.com/

它不会起作用。

路线应该像'/home'或类似的东西。

遵循official docs中的指导原则

重定向

如果您只想重定向到外部链接,可以设置新的窗口位置:

window.location = 'https://www.google.com';

像这样:

componentDidMount() {
    setTimeout(() => {
      window.location = 'https://www.google.com';
    }, 5000)
  }

无需保持renderRedirect()功能或redirect状态

© www.soinside.com 2019 - 2024. All rights reserved.