首页 > 解决方案 > MERN:react-router-dom不在 Heroku 工作

问题描述

我的应用程序的路线运行良好。您将在下面看到的所有前端路由都按预期呈现。

但是,如果您转到应用程序并键入/tournaments,否则/users它将显示原始 json,因为这是我在后端 Express 路由中为某些数据内容定义的两条路径。

所以,我找到了一个使用Redirectvia的解决方案react-router-dom,它可以工作:

验证路由.js

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
const ValidateRoute = props => {
  if(props.type === "invalid") return <Redirect to="/" />;
  else return <Route {...props} />
};
export default ValidateRoute;

应用程序.js

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { Container, Row, Col } from 'reactstrap';
import { Provider } from 'react-redux';
import store from './store';
import NavigationBar from './components/layout/NavigationBar';
import ProfileSidebar from './components/layout/ProfileSidebar';
import TournamentIndex from './components/tournaments/Index';
import TournamentShow from './components/tournaments/Show';
import TournamentStart from './components/tournaments/Start';
import PlayerProfile from './components/players/PlayerProfile';
import PlayerDirectory from './components/players/PlayerDirectory';
import News from './components/news/SmashNews';
import { loadUser } from './actions/authActions';
import ValidateRoute from './components/ValidateRoute';

export default class App extends Component{
  componentDidMount() {
    store.dispatch(loadUser());
  };

  render() {
    return (
      <Provider store={store}>
        <Router>
          <NavigationBar />
          <Container>
            <Row className="justify-content-sm-center justify-content-md-center">
              <Col sm="7" md="7" lg="5" xl="5">
                <ProfileSidebar />
              </Col>

              <Col sm="7" md="7" lg="7" xl="7">
                <Switch>
                  <Route exact path="/" component={TournamentIndex} />
                  <Route path="/tournaments/:id" component={TournamentShow} />
                  <Route path="/tournaments/:id/start" component={TournamentStart} />
                  <Route path="/players" component={PlayerDirectory} />
                  <Route path="/player/:id" component={PlayerProfile} />
                  <Route path="/smash-news" component={News} />
                  <ValidateRoute path="/tournaments" type="invalid"/>
                  <ValidateRoute path="/users" type="invalid"/>
                </Switch>
              </Col>
            </Row>
          </Container>
        </Router>
      </Provider>
    );
  };
};

这样,当我尝试/tournamentsor时/users,它仅重定向到本地主机上的主路径“/”。

然而,在 heroku 上,它仍然只显示后端 json,并且没有发生重定向。

我找不到任何解决方案,只有不完全适合这种情况的类似问题。有人有见识吗?谢谢

标签: javascriptreactjsherokureact-router-dommern

解决方案


Try to use this:

history.push(‘/‘)

Method by bringing history from react-router-dom


推荐阅读