React笔记(五)

2024 年 5 月 3 日 星期五(已编辑)
/
7
摘要
这段内容总结了SCSS、Ant Design组件库、配置@别名路径、封装requests请求模块、使用Redux管理token、token持久化、Axios请求拦截器注入Token、使用Token做路由权限控制、useLocation、token失效和Echarts的安装及使用方法。
这篇文章上次修改于 2024 年 5 月 7 日 星期二,可能部分内容已经不适用,如有疑问可询问作者。

阅读此文章之前,你可能需要首先阅读以下的文章才能更好的理解上下文。

1.SCSS

一种后缀名为.scss的预编译CSS语言

npm install sass -D

2.Ant Design组件库

最常用的React PC端组件库,快速开发PC管理后台项目

npm install antd --save

2.1 表单校验

实现步骤

  1. 为 Form 组件添加 validateTrigger 属性,指定校验触发时机的集合
  2. 为 Form.Item 组件添加 name 属性,这样表单校验才会生效 [容易忽略]
  3. 为 Form.Item 组件添加 rules 属性,用来添加表单校验
import { Form, Input, Button, Checkbox } from 'antd'
const Login = () => {
  return (
    <Form>
      <Form.Item>
        <Input size="large" placeholder="请输入手机号" />
      </Form.Item>
      <Form.Item>
        <Input size="large" placeholder="请输入验证码" />
      </Form.Item>
      <Form.Item>
        <Checkbox className="login-checkbox-label">
          我已阅读并同意「用户协议」和「隐私条款」
        </Checkbox>
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit" size="large" block>
          登录
        </Button>
      </Form.Item>
    </Form>
  )
}

3.配置@别名路径

//1.安装craco工具包
npm install @craco/craco -D

//2.craco.config.js
const path = require('path')
module.exports = {
    webpack: {
        alias: {
            '@': path.resolve(__dirname,'src')
        }
    }
}

//3.修改package.json,将start/build/test 三个命令修改为craco方式
"scripts": {
  "start": "craco start",
  "build": "craco build",
  "test": "craco test",
  "eject": "react-scripts eject"
}

4.封装requests请求模块

//axios的封装配置
import axios from 'axios'
//1.根域名的配置
//2.超时时间
//3.请求拦截 / 响应拦截

const http = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 5000,
})

// 添加请求拦截器
http.interceptors.request.use((config) => {
    return config
}, (error) => {
    return Promise.reject(error)
})

// 添加响应拦截器
http.interceptors.response.use((response) => {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response
}, (error) => {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error)
})

export { http }

5.使用Redux管理token

token是一个用户的标识数据,需要在很多个模块中共享

//1.Redux中编写获取token的异步获取和同步修改
//2.Login组件负责提交action并且把表单数据传递过来

6.token持久化

利用浏览器本地缓存LocalStorage

//存
 localStorage.setItem('token_key',token)
//取
 localStorage.getItem('token_key')
//判断
token: localStorage.getItem('token_key') || ''

7.Axios请求拦截器注入Token

请求拦截器注入Token以后,所有用到Axios实例的接口请求都会自动带上token

// 添加请求拦截器
http.interceptors.request.use((config) => {
    //1.获取token(localStorage)
    //2.拼接
    const token = getToken()
    if(token){
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, (error) => {
    return Promise.reject(error)
})

8. 使用Token做路由权限控制

利用高阶组件来判断有没有token

//封装高阶组件--AuthRouter
import { message } from "antd";
import { getToken } from "../utils";
import { Navigate } from "react-router-dom";

export function AuthRouter({ children }) {
    const token = getToken();
    if (token) {
        return <>{children}</>
    }else {
        message.error("请先登录!")
        return <Navigate to={'/login'} replace />
    }
}
//以路由组件为参数,以token有无来做判断
import { AuthRouter } from '../components/AuthRouter'

const router = createBrowserRouter([
    {
        path: '/',
        element: <App />
    },
    {
        path: '/layout',
        element: <AuthRouter> <Layout /> </AuthRouter>
    },
    {
        path: '/login',
        element: <Login />
    }
])

9.useLocation

获取当前路由路径

const location = useLocation()
console.log(location.pathname)

10.token失效

用户长时间未在网站中做任何操作且规定失效时间到达后,token就会失效

//1.在axios拦截器中监控401状态码
// 添加响应拦截器
http.interceptors.response.use((response) => {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response
}, (error) => {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error)
})
//2.清除失效token,跳转login页面

11.Echarts

//安装
npm install echarts
//使用
import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';


function Home() {
    const chartRef = useRef(null)
    useEffect(() => {
        const chartDom = chartRef.current
        const myChart = echarts.init(chartDom);

        const option = {
            xAxis: {
                type: 'category',
                data: ['Vue','React','Angular']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: [120, 200, 150],
                    type: 'bar'
                }
            ]
        };

        option && myChart.setOption(option);
    },[])
    return (
        <div>
            <h1>
                <div ref={chartRef} style={{width:'500px',height: '400px'}}></div>
            </h1>
        </div>
    )
}
  • Loading...
  • Loading...
  • Loading...
  • Loading...
  • Loading...