react context_如何使用React Context保护您的路线

react context

by paul christophe

保罗·克里斯托夫(Paul Paul Christophe)

如何使用React Context保护您的路线 (How to protect your routes with React Context)

Among the changes in React 16.3 is a new stable version of the Context API. We’re going to take a look at how it works by building a protected route component.

React 16.3的更改中,有一个新的稳定版本的Context API 。 我们将通过构建受保护的路由组件来了解其工作原理。

什么是上下文? (What is Context?)

Context is about encapsulating state. It allows us to pass data from a parent provider component to any subscribed component down the tree. Without state management we often have to “drill” props through every component along the way.

上下文是关于封装状态的。 它使我们能够将数据从父提供者组件传递到树下的任何已订阅组件。 如果没有状态管理,我们常常必须沿整个过程“钻探”道具。

那不是Redux的目的吗? (Isn’t that what Redux is for?)

Yes, Context operates similarly to how components can connect to Redux’s global state. However, a native element like Context will often be a better solution for small to medium apps that don’t need the complex overhead of Redux.

是的 ,上下文的运行方式类似于组件如何连接到Redux的全局状态。 但是,对于不需要Redux复杂开销的中小型应用程序而言,诸如Context之类的本地元素通常是更好的解决方案。

基本概念 (Basic Concepts)

There are three elements to Context:

上下文包含三个元素:

  • createContext — Calling this returns a pair of components, Provider and Consumer.

    createContext —调用此方法将返回一对组件ProviderConsumer

  • Provider — a Component that allows for one or more Consumers to subscribe to changes.

    Provider —一种组件,允许一个或多个Consumers订阅更改。

  • Consumer —a Component subscribed to a Provider

    Consumer -订阅提供程序的组件

让我们开始建设 (Let’s Start Building)

We’re going to build an app with two routes. One is a landing page with global access. The other is a dashboard page with restricted access for logged in users. You can find the final version here.

我们将使用两条路线构建一个应用程序。 一个是具有全局访问权限的登录页面 。 另一个是仪表板页面该页面具有登录用户的受限访问权限。 您可以在此处找到最终版本

Try it out: go to /dashboard while logged out. Log in and navigate freely between routes. From the dashboard, log out and it’ll kick you out to the landing page.

试用:注销后转到/ dashboard。 登录并在路线之间自由导航。 从仪表板上注销,它将带您进入登录页面。

上下文标题 (Context Header)

To demonstrate Context’s basic functionality, let’s start by building a header component that lets us log in and out. First, create our context in a new file.

为了演示Context的基本功能,让我们从构建一个标题组件开始,让我们登录和注销。 首先,在新文件中创建上下文。

/* AuthContext.js */
import React from 'react';
const AuthContext = React.createContext();

Export a component AuthProvider to define our state (whether the user is logged in) and pass its state to the value prop on the Provider. We’ll simply expose AuthConsumer with a meaningful name.

导出组件AuthProvider来定义我们的状态(无论用户是否登录),并将其状态传递给Provider上的value AuthProvider 。 我们将简单地使用有意义的名称公开AuthConsumer

/* AuthContext.js */
...
class AuthProvider extends React.Component {  state = { isAuth: false }
render() {    return (      <AuthContext.Provider        value={{ isAuth: this.state.isAuth }}      >        {this.props.children}      </AuthContext.Provider>    )  }}
const AuthConsumer = AuthContext.Consumer
export { AuthProvider, AuthConsumer }

In index.js, wrap our app in AuthProvider.

在index.js中,将我们的应用包装在AuthProvider

/* index.js */import React from 'react';import { render } from 'react-dom';import { AuthProvider } from './AuthContext';import Header from './Header';
const App = () => (  <;div>    <AuthProvider>      <Header />    </AuthProvider>  </div>);
render(<App />, document.getElementById('root'));

Now create our Header and import our AuthConsumer (I’m leaving styling out for clarity).

现在创建我们的Header并导入我们的AuthConsumer (为了清楚起见,我将保留样式)。

/* Header.js */import React from 'react'import { AuthConsumer } from './AuthContext'import { Link } from 'react-router-dom'
export default () => (  <header>    <AuthConsumer>    </AuthConsumer>  </header>)

Context Consumers must have a function as their direct child. This will be passed the value from our Provider.

上下文消费者必须具有直接孩子职能。 这将从我们的Provider传递值。

/* Header.js */...export default () => (  <header>    <AuthConsumer>
{({ isAuth }) => (        <div>          <h3>            <Link to="/">              HOME            &lt;/Link>          </h3>
{isAuth ? (            <ul>              <Link to="/dashboard">                Dashboard              </Link>              <button>                logout              </button>            </ul>          ) : (            <button>login</button>          )}        </div>      )}
</AuthConsumer>  </header>)

Because isAuth is set to false, only the login button will be visible. Try changing the value to true (it’ll switch to the logout button).

由于isAuth设置为false,因此只有登录按钮可见。 尝试将值更改为true (它将切换到注销按钮)。

Ok, let’s try switching isAuth in code. We’ll pass a login and logout function from our Provider.

好的,让我们尝试在代码中切换isAuth 。 我们将传递来自Provider的登录和注销功能。

/* AuthContext.js */...class AuthProvider extends React.Component {  state = { isAuth: false }
constructor() {    super()    this.login = this.login.bind(this)    this.logout = this.logout.bind(this)  }
login() {    // setting timeout to mimic an async login    setTimeout(() => this.setState({ isAuth: true }), 1000)  }
logout() {    this.setState({ isAuth: false })  }
render() {    return (      <AuthContext.Provider        value={{          isAuth: this.state.isAuth,          login: this.login,          logout: this.logout        }}      >        {this.props.children}      </AuthContext.Provider>    )  }}

These functions will allow us to toggle our auth state in Header.

这些功能将使我们能够切换Header的auth状态。

/* Header.js */...export default () => (  <header>    <AuthConsumer>      {({ isAuth, login, logout }) => (        <div>          <h3>            <Link to="/">              HOME            </Link>          </h3>
{isAuth ? (            <ul>              <Link to="/dashboard">                Dashboard              </Link>              <button onClick={logout}>                logout              </button>            </ul>          ) : (            <button onClick={login}>login</button>          )}        </div>      )}    </AuthConsumer>  </header>)

受上下文保护的路由 (Protected Route With Context)

Now that we have covered the basics, let’s extend what we’ve learned to create a protected route component.

既然我们已经介绍了基础知识,那么让我们扩展所学到的创建受保护路由组件的知识。

First make Landing and Dashboard page components. Our dashboard will only be visible when the user is logged in. Both pages will be as simple, as below:

首先制作Landing and Dashboard页面组件。 仅当用户登录时,我们的仪表板才可见。两个页面都将非常简单,如下所示:

/* Dashboard.js */import React from 'react'
const Dashboard = () => <h2>User Dashboard</h2>
export default Dashboard

Now let’s route to these pages.

现在,我们转到这些页面。

/* index.js */import React from 'react';import { render } from 'react-dom';import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';import { AuthProvider } from './AuthContext';import Landing from './Landing';import Dashboard from './Dashboard';import Header from './Header';
const App = () => (  <;div>    <Router>      <AuthProvider>;        <Header />        <Switch>          <Route path="/dashboard" component={Dashboard} />          <Route path="/" component={Landing} />        &lt;/Switch>      </AuthProvider>    </Router>  </div>);
render(<App />, document.getElementById('root'));

In this current state you can navigate to both / and /dashboard. We’ll make a special route component that checks if a user is logged in called ProtectedRoute. The set up is similar to our Header component.

在此当前状态下,您可以导航到//dashboard 。 我们将创建一个特殊的路由组件来检查用户是否已登录,称为ProtectedRoute 。 设置类似于我们的Header组件。

/* ProtectedRoute.js */import React from 'react';import { Route, Redirect } from 'react-router-dom';import { AuthConsumer } from './AuthContext';
const ProtectedRoute = () => (  <AuthConsumer>    {({ isAuth }) => (
)}  </AuthConsumer&gt;);
export default ProtectedRoute;

The private route will function just like a regular react-router route, so we’ll expose the component and any other props passed to it.

私有路由的功能就像常规的react-router路由一样,因此我们将公开组件和传递给它的任何其他道具。

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

Now the interesting part: we’ll use the isAuth variable to determine if it should redirect or render the protected route’s component.

现在有趣的部分:我们将使用isAuth变量来确定它是否应该重定向或呈现受保护路由的组件。

const ProtectedRoute = ({ component: Component, ...rest }) => (  <AuthConsumer>    {({ isAuth }) => (      <Route        render={          props =>            isAuth             ? <Component {...props} />             : <Redirect to="/" />        }        {...rest}      />    )}  </AuthConsumer>)

In our index file let’s import ProtectedRoute and use it on our dashboard route.

index文件中,让我们导入ProtectedRoute并在我们的仪表板路线上使用它。

/* index.js */...
<ProtectedRoute path="/dashboard" component={Dashboard} />

Awesome, now we have protected routes! Try pointing the browser to /dashboard and watch it kick you back to the landing page.

太好了,现在我们保护了路线! 尝试将浏览器指向/dashboard然后看着它将您踢回到登录页面。

Again, here’s the link for the working demo. Read more about Context from React’s Official Docs.

同样,这是工作演示的链接。 从React的官方文档中阅读有关Context的更多信息。

翻译自: https://www.freecodecamp.org/news/how-to-protect-your-routes-with-react-context-717670c4713a/

react context

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值