一、在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语法

  • 导入RouteObject
  • 导入withLoadable.tsx文件
  • 导入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中配置

导入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二次封装

导入

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'

响应拦截器封装:

导入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
        }
    }
})

请求拦截器的封装

导入axios的类型声明:InternalAxiosRequestConfig

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

请求封装

创建接口文件对请求参数进行类型限制,下面有user.ts文件

export interface IUser{
    userName:string
    password:Number
}

封装登录请求

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>
  )
}

到此这篇关于使用React和Redux Toolkit实现用户登录功能的文章就介绍到这了,更多相关React RTK实现登录内容请搜索阿兔在线工具以前的文章或继续浏览下面的相关文章希望大家以后多多支持阿兔在线工具!

点赞(0)

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部