react router 路由守卫_react-router怎么做路由守卫?

import React from "react";

import {

BrowserRouter as Router,

Route,

Link,

Redirect,

withRouter

} from "react-router-dom";

const AuthExample = () => (

  • Public Page

  • Protected Page

);

const fakeAuth = {

isAuthenticated: false,

authenticate(cb) {

this.isAuthenticated = true;

setTimeout(cb, 100); // fake async

},

signout(cb) {

this.isAuthenticated = false;

setTimeout(cb, 100);

}

};

const AuthButton = withRouter(

({ history }) =>

fakeAuth.isAuthenticated ? (

Welcome!{" "}

onClick={() => {

fakeAuth.signout(() => history.push("/"));

}}

>

Sign out

) : (

You are not logged in.

)

);

const PrivateRoute = ({ component: Component, ...rest }) => (

{...rest}

render={props =>

fakeAuth.isAuthenticated ? (

) : (

to={{

pathname: "/login",

state: { from: props.location }

}}

/>

)

}

/>

);

const Public = () =>

Public

;

const Protected = () =>

Protected

;

class Login extends React.Component {

state = {

redirectToReferrer: false

};

login = () => {

fakeAuth.authenticate(() => {

this.setState({ redirectToReferrer: true });

});

};

render() {

const { from } = this.props.location.state || { from: { pathname: "/" } };

const { redirectToReferrer } = this.state;

if (redirectToReferrer) {

return ;

}

return (

You must log in to view the page at {from.pathname}

Log in

);

}

}

使用react-router-dom创建动态路由非常简单。我们可以使用Route组件来定义路由并在其中使用动态参数。以下是如何使用react-router-dom创建动态路由的步骤: 1. 安装react-router-dom:使用以下命令安装react-router-dom。 ``` npm install react-router-dom ``` 2. 在项目中导入所需的组件: ```javascript import React from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; ``` 3. 创建路由并在其中使用动态参数: ```javascript <Router> <Switch> <Route exact path="/" component={Home} /> <<Route exact path="/users/:id" component={User} /> </Switch> </Router> ``` 上面的代码中,我们定义了一个具有动态参数的路由。用户可以通过访问URL `/users/:id` 来访问该路由。其中,`:id` 是一个动态参数,它将被替换为用户请求的实际值。 4. 在组件中获取动态参数: 在上面的代码中,我们定义了一个名为`User`的组件。我们可以在该组件中通过`props.match.params.id`来获取动态参数的值。以下是一个简单的示例: ```javascript import React from "react"; const User = (props) => { return <h1>User ID: {props.match.params.id}</h1>; }; export default User; ``` 在上面的代码中,我们使用`props.match.params.id`来获取动态参数的值,并将其显示在页面上。 这就是使用react-router-dom创建动态路由的基本步骤。你可以根据你的具体需求进行调整和修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值