react-check-auth 使用教程
项目介绍
react-check-auth 是一个用于在 React 或 React Native 应用中进行声明式身份验证检查的小型组件。它利用 React 16 的新 Context API,代码量仅约 100 行。该组件可以作为熟悉 Context API 的入门示例,帮助开发者在渲染前进行身份验证检查。
项目快速启动
安装
首先,通过 npm 或 yarn 安装 react-check-auth:
npm install react-check-auth
# 或者
yarn add react-check-auth
基本使用
- 引入组件:
import React from 'react';
import ReactDOM from 'react-dom';
import { AuthProvider, AuthConsumer } from 'react-check-auth';
- 配置 AuthProvider:
const authUrl = 'https://my-backend.com/verifyAuth';
const App = () => (
<AuthProvider authUrl={authUrl}>
<Main />
</AuthProvider>
);
- 使用 AuthConsumer:
const Main = () => (
<Router>
<Route path='/home' component={Home} />
<Route path='/login' component={Login} />
</Router>
);
const Home = () => {
return (
<AuthConsumer>
{({ userInfo }) => {
if (!userInfo) {
return <Redirect to='/login' />;
}
return <div>Welcome Home</div>;
}}
</AuthConsumer>
);
};
应用案例和最佳实践
案例1:使用 GET 端点
import React from 'react';
import { AuthProvider } from 'react-check-auth';
const authUrl = 'https://my-backend.com/verifyAuth';
const reqOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + window.localStorage.myAuthToken
}
};
const App = () => (
<AuthProvider authUrl={authUrl} reqOptions={reqOptions}>
<Main />
</AuthProvider>
);
案例2:使用 POST 端点
import React from 'react';
import { AuthProvider } from 'react-check-auth';
const authUrl = 'https://my-backend.com/verifyAuth';
const reqOptions = () => ({
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + window.localStorage.myAuthToken
}
});
const App = () => (
<AuthProvider authUrl={authUrl} reqOptions={reqOptions}>
<Main />
</AuthProvider>
);
典型生态项目
react-check-auth 可以与其他声明式组件(如路由组件)结合使用,以实现更复杂的身份验证逻辑。例如,结合 react-router 进行路由级别的身份验证检查。
import { AuthConsumer } from 'react-check-auth';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
const Main = () => (
<Router>
<Route path='/home' component={Home} />
<Route path='/login' component={Login} />
</Router>
);
const Home = () => {
return (
<AuthConsumer>
{({ userInfo }) => {
if (!userInfo) {
return <Redirect to='/login' />;
}
return <div>Welcome Home</div>;
}}
</AuthConsumer>
);
};
通过这种方式,可以在应用的各个部分进行细粒度的身份验证控制,确保只有经过身份验证的用户才能访问特定资源。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



