Я пытаюсь перенаправить пользователя на not-found
URL-адрес, когда указан неизвестный 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
is
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
is
{
"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:
после добавления маршрута с путем = "*" как,
<Switch>
<Route exact path="/not-found" component={NotFound} />
<Route path="*" component={NotFound} />
</Switch>
не сработалокак
Я пробовал это решение на StackOverflow , но я не смог применить его для частного и публичногомаршруты.