history.push(path)在react-router-dom v4中不起作用,在重定向到404时使用redux

时间:2018-11-27 20:01:14

标签: reactjs redux react-redux react-router react-router-redux

给出未知网址时,我试图将用户重定向到not-found网址,

我正在使用history.push('not-found')

但在ComponentwillReceiveProps()内无效。

  componentWillReceiveProps(nextProps) {
    if (nextProps.profile.profile === null && 
     this.props.profile.loading) {
      this.props.history.push("/not-found");
    }
  }

App.js中,使用BrowserRouter as Router, 我正在将组件NotFound渲染为

但是问题是{NotFound}仅显示到路径/not-found,而不是其他不完整的路径,

如何显示其他未指定路由的NotFound组件?

screenshot1

screenshot2 github-project-link

app.js

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Provider } from "react-redux";
import jwt_decode from "jwt-decode";
import store from "./store";

import { setCurrentUser, logoutUser } from "./actions/authActions";
import setAuthToken from "./utils/setAuthToken";
import Navbar from "./components/layout/Navbar";
import Footer from "./components/layout/Footer";
import Landing from "./components/layout/Landing";
import Register from "./components/auth/Register";
import Login from "./components/auth/Login";
import Dashboard from "./components/dashboard/Dashboard";
import CreateProfile from "./components/create-profile/CreateProfile";
import EditProfile from "./components/edit-profile/EditProfile";
import AddExperience from "./components/add-credentials/AddExperience";
import AddEducation from "./components/add-credentials/AddEducation";
import Profiles from "./components/profiles/Profiles";
import Profile from "./components/profile/Profile";

import PrivateRoute from "./components/common/PrivateRoute";
import NotFound from "./components/not-found/NotFound";

import "./App.css";
import { clearCurrentProfile } from "./actions/profileActions";

// check if token is stored in localstorage, if user has logged in.

if (localStorage.jwtToken) {
  // if token exitst, then set auth token header auth
  setAuthToken(localStorage.jwtToken);

  // now decode token and get user-info, expiry-date of token
  const decoded = jwt_decode(localStorage.jwtToken);

  // set user and user is now authenticated
  store.dispatch(setCurrentUser(decoded));

  // check for expired date of token
  const currentTime = Date.now() / 1000;
  if (decoded.exp < currentTime) {
    // exp should be greater to keep alive login
    store.dispatch(logoutUser());

    // Logout user and clear it's profile
    store.dispatch(clearCurrentProfile());
  }
}

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Router>
          <div className="App">
            <Navbar />
            <Route exact path="/" component={Landing} />
            <div className="container">
              <Route exact path="/register" component={Register} />
              <Route exact path="/login" component={Login} />
              <Route exact path="/profiles" component={Profiles} />
              <Route exact path="/profile/:handle" component={Profile} />
              <Switch>
                <PrivateRoute exact path="/dashboard" component={Dashboard} />
              </Switch>
              <Switch>
                <PrivateRoute
                  exact
                  path="/create-profile"
                  component={CreateProfile}
                />
              </Switch>
              <Switch>
                <PrivateRoute
                  exact
                  path="/edit-profile"
                  component={EditProfile}
                />
              </Switch>
              <Switch>
                <PrivateRoute
                  exact
                  path="/add-experience"
                  component={AddExperience}
                />
              </Switch>
              <Switch>
                <PrivateRoute
                  exact
                  path="/add-education"
                  component={AddEducation}
                />
              </Switch>
              <Route exact path="/not-found" component={NotFound} />
              <Route component={NotFound} />
            </div>
            <Footer />
          </div>
        </Router>
      </Provider>
    );
  }
}

export default App;

package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "classnames": "^2.2.6",
    "moment": "^2.22.2",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-moment": "^0.8.2",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.0.5",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "proxy": "http://localhost:5000",
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

connect-geeks/frontend/src/components/profile/Profile.js文件中,

我正在使用方法history.push(path)

withRouter也没有用,将connect()包装在其中。

修改1:

在添加路径为“ *”的Route后,

<Switch>
     <Route exact path="/not-found" component={NotFound} />
     <Route path="*" component={NotFound} />
</Switch>

它不起作用

screenshot

我尝试了this solution on StackOverflow,但无法将其应用于私人和公共路线。

1 个答案:

答案 0 :(得分:0)

使用Route向路由器添加新的path="*",它将捕获所有未映射的路由。

<Route path="*" component={NotFound}/>

我建议您阅读以下内容:React-Router v4 - Handling 404 pages