now the company"s background system uses Ant Financial Services Group"s dva.js, react+redux-based encapsulation, using dva-cli, now to do login authentication. There seems to be no beforeEach hook function in
react-router-dom similar to the beforeEach hook function in vue, which can intercept routes.
import React from "react";
import { Router, Route, Switch, Redirect } from "dva/router";
import routerList from "./common/routerList";
import Error404 from "./routes/Error/Error404";
export default function RouterConfig({ history, app }) {
const token = app._store.getState().user.token;
console.log("router get token: ", token);
const Routers = routerList.map((item, index) => {
return <Route key={index} path={item.path} exact render={(props) => {
if (item.noAuth) { //
return <item.component {...props} />;
} else {
if (token) {
return <item.component {...props} />;
} else {
return <Redirect to={{
pathname: "/login",
state: {from: props.location} }} />
}
}
}} />
});
return (
<Router history={history}>
<Switch>
{Routers}
<Route path="/" exact render={() => (
<Redirect to="/article/mylist" />
)} />
<Route component={Error404} />
</Switch>
</Router>
);
}
this is my route interception, but it will only have an effect after entering the page for the first time or after the page is refreshed.
and then when you log in, you can"t jump to the home page using this.props.history.push () or this.props.history.replace ()
this.props.dispatch({
type: "user/saveUserInfo",
payload: { userId, nickName, headImageUrl, userName }
});
this.props.dispatch({
type: "user/saveToken",
payload: token
});
let RedirectUrl = this.props.location.state ? this.props.location.state.from.pathname : "/";
console.log(RedirectUrl);
this.props.history.replace(RedirectUrl);