【问题标题】:How to avoid 404 page in react-router?如何避免 react-router 中的 404 页面?
【发布时间】:2020-02-13 01:33:46
【问题描述】:

我正在研究一个使用 React Router 的简单示例。

我使用 create-react-app 创建它

在本地服务器上,每个链接都运行良好 ex) localhost:3000/login、localhost:3000/product 等

部署到我的域后,我在输入链接时收到 404 错误。 例如)myDomain.com/login、myDomain.com/product

在本地服务器上看起来不错,所以我认为源代码没有问题。

然后,当出现 404、403 ... 等页面时,我收到了重定向到 index.html 页面的答案

localhost:3000 和 localhost:3000/index.html 是一样的吗?

在主页(本地主机:3000 或 myDomain.com)上, 渲染得很好。

在 index.html (localhost: 3000 / index.html 或 myDomain.com/index.html) 它只在 {Home} 上方呈现最多 h1 标记。从这里有什么问题吗?

请帮帮我T.T

App.js


class App extends Component{
  render(){        
    return (
      <div className="App">
        <Header/>
        <h1>asd</h1>
        <h1>asd</h1>
        <Route exact path = "/" component = {Home}/>
          <Route path = "/about" component = {About}/>
          <Route path = "/event" component = {Event}/>
          <Route path = "/qna" component = {QnA}/>
          <Route path = "/login" component = {Login}/>
          <Route path = "/join" component = {Join}/>
          <Route path = "/product" component = {Product}/>
      </div>
    );
  }
}

export default App;

Root.js


const Root = () => {
    return (
        <BrowserRouter>
            <App/>
        </BrowserRouter>

    );
};

export default Root;

【问题讨论】:

  • 你可以在你的应用中访问/路由吗?

标签: javascript reactjs react-router


【解决方案1】:

您可以将您的路由组件包装在一个开关组件中,如果没有匹配项,则呈现一个默认组件,如下所示。

<Switch>
    <Route exact path = "/" component = {Home}/>
    <Route path = "/about" component = {About}/>
    <Route path = "/event" component = {Event}/>
    <Route path = "/qna" component = {QnA}/>
    <Route path = "/login" component = {Login}/>
    <Route path = "/join" component = {Join}/>
    <Route path = "/product" component = {Product}/>
    <Route component={NoMatch} />
</Switch>

显然,您可以将 NoMatch 组件更改为您想要的默认组件。

【讨论】:

    【解决方案2】:

    您应该将基本名称添加到根中的 BrowserRouter 组件

    ReactDOM.render(
      <BrowserRouter basename='/My-App/'>
        <React.StrictMode>
          <App />
        </React.StrictMode>
      </BrowserRouter>
      ,
      document.getElementById('root')
    );
    

    此外,您应该确保在 404 情况下您被重定向到 index.html,因为它是一个 SPA,并且一切都在那里发生,您只需将此行替换为 package.json 中的“build”脚本即可

     "build": "react-scripts build && cp build/index.html build/404.html",
    

    【讨论】:

    • 我喜欢你的想法/方法。只是它对我不起作用。我收到一个错误:'cp' 未被识别为内部或外部命令,
    【解决方案3】:

    我认为这不是您的 react 应用程序问题,而是您的应用程序的部署方式。

    我希望您已经使用生产版本(使用npm run build)部署了您的应用程序。 如果是这样,这很可能是您的 Web 服务器没有重定向到正确的条目。

    您需要告诉您的网络服务器(无论您使用的是 nginx 还是 caddy)在点击 404 时指向 /index.html。这是 nginx 的简单配置。

    https://www.barrydobson.com/post/react-router-nginx/

    【讨论】:

      猜你喜欢
      • 2018-11-14
      • 1970-01-01
      • 2021-06-13
      • 2023-01-29
      • 2021-02-01
      • 2018-07-11
      • 2021-12-02
      • 2019-08-18
      • 2021-05-12
      相关资源
      最近更新 更多