如何使用reactjs正确路由到动态页面? 404页面无法访问

时间:2019-06-28 00:20:12

标签: reactjs react-router-dom

由于{Error404}无法访问,我应该修复另一个开发人员创建的代码。代码按原样将除先前指定的路径以外的所有页面发送到InternalPage page = {page}。因此,当site / {route}不存在时,将显示一个空的InternalPage html,而不是在Route组件中配置的404页面。

import React, { Component } from "react";
import PropTypes from 'prop-types';
import { BrowserRouter, Route, Switch } from "react-router-dom";

import Home from "./containers/Home";
import Results from "./containers/Results";
import Pages from "./containers/Pages";
import Inspiration from "./containers/Inspiration";

import Header from "./components/Header";
import Footer from "./components/Footer";
import Error404 from "./components/Error404";

import PagesNav from "./components/PagesNav";
import InternalPage from "./components/InternalPage";

const internalPages = [
  "About",
  "Terms",
  "Help",
  "Cookies",
  "Privacy",
  "Partnerships"
]

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      lang:"en",
      currency: "EUR"
    }
  }
  componentWillMount() {
    var lang = navigator.language || navigator.userLanguage;
    lang = lang.split("-")[0] === "it" ? "it" : "en";
    this.setState({lang})
  }
  render() {
    return (
        <BrowserRouter>
          <div>
            <Route render={() => <Header changeLang={lang => this.setState({lang})} lang={this.state.lang} changeCurrency={currency => this.setState({currency})} currency={this.state.currency}/>} />
            <Switch>
              <Route exact path="/" render={() => <Home lang={this.state.lang} currency={this.state.currency}/>} />
              <Route exact path="/Results" render={() => <Results lang={this.state.lang} currency={this.state.currency} mixpanel={this.context.mixpanel}/>} />
              <Route exact path="/Inspiration" render={() => <Inspiration lang={this.state.lang} currency={this.state.currency} mixpanel={this.context.mixpanel}/>} />
                <Pages>
                  <PagesNav />
                  <article>
                    {internalPages.map(page => <Route key={page} exact path={`/${page}`} render={() => <InternalPage page={page} lang={this.state.lang}/>}/>)}
                  </article>
              </Pages>
              <Route component={Error404} />
            </Switch>
            <Route render={() => <Footer changeLang={lang => this.setState({lang})} lang={this.state.lang}/>} />
        </div>
      </BrowserRouter>
    )
  }
}
App.contextTypes = {
  mixpanel: PropTypes.object.isRequired
}
export default App;

能否请您指出解决此路由问题的更好方法?我尝试了其他几种选择,但均未成功,例如,页面404出现了,但通往/ [InternalPages]的路由中断了。

1 个答案:

答案 0 :(得分:0)

在路由代码的底部放置一个不完全路由,该路由会将所有未指定的页面带到404组件:

<Route path="/" component={Error404} />