首页 > 解决方案 > `window.location.href` 在 github 页面上部署时不适用于 react 应用程序

问题描述

有一个类似的问题,但我的问题是不同的。

在 localhost 上运行react应用程序时,它会从以下页面导航,

在此处输入图像描述

提交按钮有代码window.location.href = "/ahana-psychometry/assessments/"; 所以它导航到页面:

在此处输入图像描述

但是当我按下 gh-pages 页面上的提交按钮时,url 会从blenderous.github.io/ahana-psychometry/create变为blenderous.github.io/ahana-psychometry/assessments/. 但

在此处输入图像描述

但页面显示的是 404 消息:

在此处输入图像描述

标签: reactjsreact-routergithub-pages

解决方案


当您使用反应路由器时,最好的方法是使用它的方法。

这是一个示例,描述了使用 withRouter HOC 重定向到另一个页面:

import {
  withRouter
} from 'react-router-dom'

class Sample extends React.Component {
  handleSubmit = (e) => {
    ...
    this.props.history.push('/ahana-psychometry/')
  }
  render() {
    return (
      <div>
        <h1>Form</h1>
        <Form onSubmit={this.handleSubmit} />
      </div>
    )
  }
}

export default withRouter(Sample)

推荐阅读