【问题标题】:history.push(path) is not working in react-router-dom v4, with redux while redirecting to 404history.push(path) 在 react-router-dom v4 中不起作用,在重定向到 404 时使用 redux
【发布时间】:2019-04-29 15:22:58
【问题描述】:

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

我也使用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 组件?

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:

添加带有 path="*" 的路由后,

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

它没有起作用

我尝试了this solution on StackOverflow,但我无法将它应用于私有和公共路由。

【问题讨论】:

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


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢,它适用于未指定的路线,但它出现在所有其他路线上,因为这个 imgur.com/a/nKQF5pT 和整个代码在这里 github.com/ganesh-deshmukh/connect-geeks/commits/master
  • @ganeshdeshmukh,尝试将path="*" 添加到组件Route
  • path="*"添加到后不起作用,同样的问题仍然存在。
  • @ganeshdeshmukh 问题是你已经为not-found 创建了另一个&lt;Switch&gt;,然后,它总是会被渲染。尝试让它与其他路线一起使用
猜你喜欢
  • 2019-07-30
  • 2020-09-02
  • 2018-05-21
  • 2021-02-01
  • 2021-07-24
  • 2021-07-27
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
相关资源
最近更新 更多