您现在的位置是:首页 >学无止境 >React+RTK登录网站首页学无止境

React+RTK登录

Miketutu 2024-06-14 17:17:43
简介React+RTK登录

一、在utils创建loadable.tsx文件

这里是tsx文件,不是ts文件,因为ts文件不识别jsx语法
因为loadable是异步加载,返回的是promise,所以需要对返回的promise进行类型限制

import  Loadable  from "react-loadable.tsx";
const withLoadable = (component:()=>Promise<any>)=>{
        return Loadable({
            loader:component,
            loading:()=><div>加载中</div>,
        })
}
export default withLoadable

二、在router文件下创建routes.tsx

这里是tsx文件,不是ts文件,因为ts文件不识别jsx语法

  1. 导入RouteObject
  2. 导入withLoadable.tsx文件
  3. 导入Login组件
    import {RouteObject} from 'react-router-dom'
    import withLoadable from 'withLoadable.tsx文件地址'
    const Login = withLoadable(()=>import('Login.tsx地址'))
    const routes:Array<RouteObject> = [
        {
            path:'/login'
            element:</Login>
        }
    ]

三、在index.tsx中配置

  1. 导入Browser
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom'
const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

四、App.tsx文件配置

useRoutes是Hook组件

import {useRoutes} from 'react-router-dom'
import routes from 'routes地址'
import React from 'react';
function App() {
  return useRoutes(routes)
}
export default App;

axios二次封装

  1. 导入
import axios,{InternalAxiosRequestConfig,AxiosResponse,AxiosError} from 'axios'
import {TOKEN_KEY} from '../utils/contant'
import {getToken,removeToken} from '../utils/h5Stroe'
import {message} from 'antd'
import {REQUESTURLERROR,TOKENVALDATE} from '../utils/contant'
  1. 响应拦截器封装:

导入axios的类型声明:AxiosResponse

newAxios.interceptors.response.use((response:AxiosResponse)=>{
    return response
},(error:AxiosError)=>{
    if(error.response){
        switch(error.response.status){
            case 404:
                message.warning(REQUESTURLERROR)
                break;
            case 401:
                message.warning(TOKENVALDATE)
                removeToken(TOKEN_KEY)
                break
        }
    }
})
  1. 请求拦截器的封装

导入axios的类型声明:InternalAxiosRequestConfig

// 请求拦截器
newAxios.interceptors.request.use((req:InternalAxiosRequestConfig)=>{
        req.headers.Authorization =  getToken(TOKEN_KEY)
        return req
})

请求封装

  1. 创建接口文件对请求参数进行类型限制,下面有user.ts文件
export interface IUser{
    userName:string
    password:Number
}
  1. 封装登录请求
import request  from "../../utils/axiosApi";
import {IUser} from '../../types/users'
export default {
    login:(data:IUser)=>request.post('/users/login',data)
}

组件配置

import React from 'react'
import {Form,Button,Card,Input, message} from 'antd'
import { UserOutlined, LockOutlined} from '@ant-design/icons'
import $api from '../api/index'
import {IUser} from '../types/users'
import * as contant from '../utils/contant'
import {setToken} from '../utils/h5Stroe'
import {TOKEN_KEY} from '../utils/contant'
import {useNavigate} from 'react-router-dom'
export default function Login() {
  const nav = useNavigate()
  const loginApi = async(arg:IUser)=>{
      const result = await $api.user.login(arg)
      console.log(result);
        if(result.data.code){
          setToken(TOKEN_KEY,result.data.token)
          message.success(contant.LoginSuccess)
          nav('/')
        }
  }
  return (
    <div>
      <Card style={{width:'500px'}}>
        <Form onFinish={loginApi}>
          <Form.Item label='账号' name='username' rules={[{ required:true, message:contant.USERNOTNULL}]}>
            <Input prefix={<UserOutlined></UserOutlined>} placeholder='请输入用户名'></Input>
          </Form.Item>

          <Form.Item label='密码' name='password' rules={[{ required:true, message:contant.PASSWORDNOTNULL}]}>
            <Input prefix={<LockOutlined></LockOutlined>} placeholder='请输入密码'></Input>
          </Form.Item>

          <Form.Item>
            <Button type='primary' htmlType='submit'>登录</Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。