有一种对URL身份验证的需求:
import React from "react";
import { connect } from "react-redux";
import { Switch, Route, Redirect } from "react-router-dom";
...
const IndexRouter = ({ loggedIn }) => (
<Switch>
<Route
path="/"
render={() => (loggedIn ? <Redirect to="/dashboard" /> : <Login />)}
/>
<Route exact path="/dashboard" component={DashboardRouter} />
<Route exact path="/stock" component={StockRouter} />
</Switch>
);
export default connect(
state => ({
loggedIn: state.persist.loggedIn
}),
{}
)(IndexRouter);
该代码意味着,如果我尚未登录,则客户端需要的所有url都将重定向到Login
组件。除此之外,它将路由到DashboardRouter
。
StockRouter
是与DashboardRouter
相关的另一条路由。
问题是,如果我登录了。我手动键入了所有不确定的URL(/dashboard
,/stock
除外),显示了/dashboard
URL,没有任何内容。诸如/stock
之类的特定网址可以直接显示组件StockRouter
。
答案 0 :(得分:0)
您需要在路由周围编写一个PrivateRoute
包装器,并更改IndexRouter中路由的顺序,以使路径为/
的路由最后匹配,否则所有路由都将匹配{{ 1}},并且无法正确显示
/
有关更多详细信息,请选中Performing Authentication on Routes with react-router-v4
答案 1 :(得分:0)
只需创建一个这样的历史记录组件:
import React from "react";
import {withRouter} from "react-router";
let globalHistory = null;
class HistoryComponent extends React.Component {
componentWillMount() {
const {history} = this.props;
globalHistory = history;
}
componentWillReceiveProps(nextProps) {
globalHistory = nextProps.history;
}
render() {
return null;
}
}
export const GlobalHistory = withRouter(HistoryComponent);
export default function gotoRoute(route) {
return globalHistory.push(route);
}
然后导入到您的组件中
import gotoRoute from "../../history";
gotoRoute({
pathname: "/your_url_here",
state: {
id: this.state.id
}
});
在index.js中
import {GlobalHistory} from "./history";
ReactDOM.render((
<Provider store={store}>
<BrowserRouter >
<div>
<GlobalHistory/>
<App/>
</div>
</BrowserRouter>
</Provider>
), document.getElementById('root'));