iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >在React项目中使用TypeScript详情
  • 619
分享到

在React项目中使用TypeScript详情

2024-04-02 19:04:59 619人浏览 安东尼
摘要

目录项目目录及ts文件划分在项目中使用typescript具体实践组件声明React Hooks使用useStateuseRefuseCallbackuseMemouseContex

前言:

本文主要记录我如何在React项目中优雅的使用TypeScript,来提高开发效率及项目的健壮性。

项目目录及ts文件划分

由于我在实际项目中大部分是使用umi来进行开发项目,所以使用umi生成的目录来做案例。

.
├── README.md
├── global.d.ts
├── mock
├── package.JSON
├── src
│   ├── assets
│   ├── components
│   │   └── PublicComA
│   │       ├── index.d.ts
│   │       ├── index.less
│   │       └── index.tsx
│   ├── layouts
│   ├── models
│   ├── pages
│   │   ├── PageA
│   │   │   ├── index.d.ts
│   │   │   ├── index.less
│   │   │   └── index.tsx
│   │   ├── index.less
│   │   └── index.tsx
│   └── utils
├── tsconfig.json
├── typings.d.ts
└── yarn.lock

在项目根目录下有typings.d.ts和global.d.ts这两个文件, 前者我们可以放置一些全局的导出模块,比如CSS,less, 图片的导出声明;后者可以放一些全局声明的变量, 接口等, 比如说window下全局变量的声明等。

如下:

// typings.d.ts
declare module '*.css';
declare module '*.less';
declare module "*.png";
declare module "*.jpeg";
declare module '*.svg' {
  export function ReactComponent(props: React.SVGProps<SVGSVGElement>): React.ReactElement
  const url: string
  export default url
}
// global.d.ts
interface Window {
  helloWorld: () => void;
}

接下来介绍一下src目录:

  • assets 存放静态资源如图片/视频/音频等, 参与webpack的打包过程
  • layouts 存放公共布局
  • components 存放全局公共组件
  • models dva的models文件夹
  • pages 存放页面的目录, 内部可以有页面组件components, 结构类似于全局的components
  • utils 存放js工具库, 请求库等公共js文件

在pages和components中有存放当前组件/页面所需要的类型和接口声明的index.d.ts。另外如models中的文件由于是每个model私有类型和接口声明,所以可以直接在文件内部去声明。 具体的目录规划如上,可以根据实际项目来做更合理的划分。

在项目中使用TypeScript具体实践

组件声明

  • 数组件 推荐使用React.FC<P={}>来表示函数类型,当使用该类型定义组件时,props中会默认带有children属性。
interface IProps {
  count: number
}

const App: React.FC<IProps> = (props) => {
  const {count} = props;
  return (
    <div className="App">
      <span>count: {count}</span>
    </div>
  );
}
  • 类组件 类组件接受两个参数,第一个是props的定义,第二个是state的定义,如果使用React.PureComponent<P, S={} SS={}>定义组件,则还有第三个参数,表示getSnapshotBeforeUpdate的返回值。
interface IProps {
  name: string;
}

interface IState {
  count: number;
}

class App extends React.Component<IProps, IState> {
  state = {
    count: 0
  };
  render() {
    return (
      <div>
        {this.state.count}
        {this.props.name}
      </div>
    );
  }
}

React Hooks使用

useState

声明定义:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
// convenience overload when first argument is omitted
	
    
function useState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];
  

如果初始值能够体现出类型,那么可以不用手动声明类型,TS会自动推断出类型。如果初始值为null或者undefined则需要通过泛型显示声明类型。

如下:

const [count, setCount] = useState(1);
const [user, setUser] = useState<IUser | null>(null);

useRef

声明定义:

 function useRef<T>(initialValue: T): MutableRefObject<T>;
 // convenience overload for refs given as a ref prop as they typically start with a null value
 

使用该Hook时,要根据使用场景来判断传入泛型类型,如果是获取DOM节点,则传入对应DOM类型即可;如果需要的是一个可变对象,则需要在泛型参数中包含'| null'。

如下:

// 不可变DOM节点,只读
const inputRef = useRef<htmlInputElement>(null);

// 可变,可重新复制
const idRef = useRef<string | null>(null);
idRef.current = "abc";

useCallback

声明定义:

 function useCallback<T extends (...args: any[]) => any>(callback: T, deps: DependencyList): T;
 

useCallback会根据返回值自动推断出类型,如果传入的参数不指定类型,则会默认为any,所以为了严谨和可维护性,一定要指定入参的类型。也可以手动传入泛型指定函数类型。

如下:

// 会自动推导出类型: (a: number, b: number) => number;
const add = useCallback((a: number, b: number) => a + b, [a, b])

// 传入泛型,则指定函数类型
const toggle = useCallback<(a: number) => number>((a: number) => a * 2, [a])

useMemo

声明定义:

function useMemo<T>(factory: () => T, deps: DependencyList | undefined): T;
   

useMemo和useCallback类似,只是定义类型为具体返回值的类型,而不是函数的类型。

如下:

// 会自动推导出类型: number;
const add = useCallback((a: number, b: number) => a + b, [a, b])

// 传入泛型,则指定函数类型
const toggle = useCallback<number>((a: number) => a * 2, [a])

useContext

声明定义:

function useContext<T>(context: Context<T>): T;

useContext会根据传入的上下文对象自动推导出context的类型,当然也可以使用泛型来设置context的类型,

如下:

interface ITheme {
	color: string;
}
const ThemeContext = React.createContext<ITheme>({ color: "red" });

// 自动推导出类型为ITheme
const theme = useContext(ThemeContext); // 等同于const theme = useContext<ITheme>(ThemeContext);

useReducer

声明定义:

function useReducer<R extends Reducer<any, any>>(
    reducer: R,
    initialState: ReducerState<R>,
    initializer?: undefined
): [ReducerState<R>, Dispatch<ReducerAction<R>>];

上面只列出了一种类型定义,我在项目中也是使用这种定义去指定useReducer的类型。普通的案例如下:

type StateType = {
  name: string;
  age: number;
}

type Actions = {
  type: 'Change_Name';
  payload: string;
} | {
  type: 'Change_Age';
  payload: number;
}

const initialState = {
  name: '小明',
  age: 18
}

const reducerAction: Reducer<StateType, Actions> = (
  state,
  action,
) => {
  switch (action.type) {
    case 'Change_Name':
      return { ...state, name: action.payload };
    case 'Change_Age':
      return { ...state, age: action.payload };
    default:
      return state;
  }
};

function Index() {
  const [state, dispatch] = useReducer(reducerAction, initialState);
  return (
    <div>
      <div>姓名:{state.name}</div>
      <div>年龄:{state.age}</div>
    </div>
  );
}

可以看到,这样能够得到正确的类型推断,但是略微繁琐。

案例如下:

// 定义一个生成Action类型的泛型
type ActionMap<M extends Record<string, any>> = {
  [Key in keyof M]: M[Key] extends undefined
    ? {
        type: Key
      }
    : {
        type: Key
        payload: M[Key]
      }
}

type StateType = {
  name: string;
  age: number;
}

// 定义具体的Action类型
type PayloadType = {
  Change_Name: string;
  Change_Age: number;
}


type Actions = ActionMap<PayloadType>[keyof ActionMap<PayloadType>]

const initialState = {
  name: '小明',
  age: 18
}

const reducerAction: Reducer<StateType, Actions> = (
  state,
  action,
) => {
  switch (action.type) {
    case Types.Name:
      return { ...state, name: action.payload };
    case Types.Age:
      return { ...state, age: action.payload };
    default:
      return state;
  }
};

我们定义了一个ActionMap泛型,该泛型会将传入的类型{key: value}生成为新的{key: {type: key, payload: value }类型。然后我们利用keyof关键字获取到所有的key,就可以得到我们所需要的{type: key1, payload: value1} | {type: key2, payload: value2}的类型了。只要我们定义好PayloadType类型,则可以自动推导出我们需要的Actions类型。

useImperativeHandle

声明定义:

  function useImperativeHandle<T, R extends T>(ref: Ref<T>|undefined, init: () => R, deps?: DependencyList): void;
  // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref<T>
  

useImperativeHandle可以让自定义组件通过ref属性,将内部属性暴露给父组件进行访问。因为是函数式组件,所以需要结合forwardRef一起使用。

案例如下:

interface FancyProps {}

interface FancyRef {
  focus: () => void;
}
const FancyInput = forwardRef<FancyRef, FancyProps>((props, ref) => {
  const inputRef = useRef<HTMLInputElement>(null);
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current?.focus();
    }
  }));
  return (
    <input ref={inputRef} {...props} />
  );
})
const Parent = () => {
  // 定义子组件ref
  const inputRef = useRef<FancyRef>(null);
  return (
    <div>
      <FancyInput 
        ref={inputRef}
      />
      <button 
        onClick={() => {
          // 调用子组件方法
          inputRef.current?.focus();
        }}
      >聚焦</button>
    </div>
  )
}

Axios请求/响应定义封装

axios是很流行的Http库,他的ts封装已经很完美了,我们只做简单的二次封装,返回通用的数据响应格式。 首先在utils/request.ts中创建一个构造axios实例的生成器:

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

// 拦截器定义
export interface RequestInterceptors {
  // 请求拦截
  requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorsCatch?: (err: any) => any
  // 响应拦截
  responseInterceptors?: (config: AxiosResponse) => AxiosResponse
  responseInterceptorsCatch?: (err: any) => any
}

// 生成axios实例的参数,实例可以单独传入拦截器
export interface RequestConfig extends AxiosRequestConfig {
  interceptorsObj?: RequestInterceptors
}

// loading请求数量
let loadinGCount: number = 0;

// 打开loading
const showLoading = () => {
  loadingCount ++;
  if(loadingCount > 0) {
    // 显示loading
    // Loading.show()
  }
}

// 关闭loading
const hideLoading = () => {
  loadingCount --;
  if(loadingCount <= 0) {
    // 隐藏loading
    // Loading.hide();
  }
}

function RequestBuilder(config: RequestConfig) {
  const { interceptorsObj, ...res } = config;

  const instance: AxiosInstance = axios.create(res);

  // 全局请求拦截器
  instance.interceptors.request.use(
    (request: AxiosRequestConfig) => {
      // 显示loading
      showLoading();
      console.log('全局请求拦截器');
      // TODO:全局的请求头操作等等
      return request;
    },
    (err: any) => err,
  )

  
  instance.interceptors.request.use(
    interceptorsObj?.requestInterceptors,
    interceptorsObj?.requestInterceptorsCatch,
  )

  
  instance.interceptors.response.use(
    interceptorsObj?.responseInterceptors,
    interceptorsObj?.responseInterceptorsCatch,
  )
  
  // 全局响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      console.log('全局响应拦截器');
      // 关闭loading
      hideLoading();
      // TODO: 通用的全局响应处理,token过期重定向登录等等
      // 返回值为res.data,即后端接口返回的数据,减少解构的层级,以及统一响应数据格式。
      return response.data
    },
    (err: any) => {
      // 关闭loading
      hideLoading();
      // TODO: 错误提示等
      return err;
    },
  )

  return instance;
}
export const http = RequestBuilder({baseURL: '/api'});

该生成器可以实现每个实例有单独的拦截器处理逻辑,并且实现全局的loading加载效果,全局拦截器的具体实现可以根据项目实际需求进行填充。生成器已经完成,但是还没法定制我们的通用响应数据,接下来我们在typings.d.ts中重新定义axios模块:

import * as axios from 'axios';
declare module 'axios' {
  // 定制业务相关的网络请求响应格式, T 是具体的接口返回类型数据
  export interface CustomSuccessData<T> {
    code: number;
    msg?: string;
    message?: string;
    data: T;
    [keys: string]: any;
  }
  export interface AxiosInstance {
    // <T = any>(config: AxiosRequestConfig): Promise<CustomSuccessData<T>>;
    request<T = any, R = CustomSuccessData<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
    get<T = any, R = CustomSuccessData<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
    delete<T = any, R = CustomSuccessData<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
    head<T = any, R = CustomSuccessData<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
    post<T = any, R = CustomSuccessData<T>, D = any>(
      url: string,
      data?: D,
      config?: AxiosRequestConfig<D>,
    ): Promise<R>;
    put<T = any, R = CustomSuccessData<T>, D = any>(
      url: string,
      data?: D,
      config?: AxiosRequestConfig<D>,
    ): Promise<R>;
    patch<T = any, R = CustomSuccessData<T>, D = any>(
      url: string,
      data?: D,
      config?: AxiosRequestConfig<D>,
    ): Promise<R>;
  }
}

完成以上操作后,我们在业务代码中具体使用:

import { http } from '@/utils/request';

interface Req {
  userId: string;
}

interface Res {
  userName: string;
  userId: string;
}

// 获取用户信息接口
const getUserInfo = async (params: Req) => {
  return http.get<Res>('/getUserInfo', {params})
}

这个时候getUserInfo返回的就是CustomSuccessData<Res>类型的数据了。至此我们对axios简单的封装也就完成了。

到此这篇关于在React项目中使用TypeScript详情的文章就介绍到这了,更多相关React使用TypeScript内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 在React项目中使用TypeScript详情

本文链接: https://www.lsjlt.com/news/167943.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 在React项目中使用TypeScript详情
    目录项目目录及ts文件划分在项目中使用TypeScript具体实践组件声明React Hooks使用useStateuseRefuseCallbackuseMemouseContex...
    99+
    2022-11-13
  • TypeScript在React项目中的使用实践总结
    序言 本文会侧重于TypeScript(以下简称TS)在项目中与React的结合使用情况,而非TS的基本概念。关于TS的类型查看可以使用在线TS工具👉TypeScri...
    99+
    2022-11-12
  • React项目中应用TypeScript的实现
    目录一、前言 二、使用方式 无状态组件 有状态组件 受控组件 三、总结 一、前言 单独的使用typescript 并不会导致学习成本很高,但是绝大部分前端开发者的项目都是依赖于框架...
    99+
    2022-11-12
  • 关于怎么在vue项目里写react详情
    我们可以直接创建jsx/tsx文件 这次的项目结构是这样的: 在vue文件里这么使用 // index.vue <template> <div class...
    99+
    2022-11-12
  • 怎么使用React+umi+typeScript创建项目
    本篇内容主要讲解“怎么使用React+umi+typeScript创建项目”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么使用React+umi+typeScript创建项目”吧!项目框架搭建...
    99+
    2023-07-05
  • 项目中使用TypeScript的TodoList实例详解
    目录为什么用todolisttodolist的ts化数据到视图实现handleTodoItemreadonly分类交叉类型新增功能联合类型可选属性数据转视图总结为什么用todolis...
    99+
    2023-01-04
    TypeScript TodoList使用 TypeScript TodoList
  • 如何在Vue3.0 项目中使用TypeScript 和 Vite
    如何在Vue3.0 项目中使用TypeScript 和 Vite?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。Vue的优点Vue具体轻量级框架、简单易学、双向数据绑定、组件...
    99+
    2023-06-06
  • 怎么在React项目中使用Redux
    这篇文章主要介绍“怎么在React项目中使用Redux”,在日常操作中,相信很多人在怎么在React项目中使用Redux问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么在R...
    99+
    2022-10-18
  • 如何在React项目中使用AntDesign
    目录0.前言1.AntDesign是什么?2.AntDesign如何使用?3.如何具体使用AntDdesign的组件3-1.如何使用 antd 的Table组件3-2.如何使用 an...
    99+
    2022-11-13
  • 项目中使用Typescript封装axios
    目录写在前面基础封装拦截器封装类拦截器实例拦截器接口拦截封装请求方法取消请求准备工作取消请求方法的添加与删除取消请求方法测试测试请求方法测试取消请求写在最后写在前面 虽然说Fetch...
    99+
    2022-11-13
  • vue项目中如何使用typescript
    本篇内容主要讲解“vue项目中如何使用typescript”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue项目中如何使用typescript”吧!1、引入Typescriptnpm ...
    99+
    2023-06-21
  • 在React、Vue项目中如何使用SVG
    这篇文章将为大家详细讲解有关在React、Vue项目中如何使用SVG,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。在一些现代的扁平化设计网站,特别是移动端网站,经常会包含...
    99+
    2022-10-19
  • 如何在Vue项目中应用TypeScript类
    目录一、前言二、使用1.@Component2.compued、data、methods3.@props4.@watch5.@emit三 、总结 一、前言 TypeScript是基于...
    99+
    2022-11-12
  • React项目中使用Redux的 react-redux
    目录背景UI 组件容器组件connect()mapStateToProps()mapDispatchToProps()组件实例:计数器背景 在前面文章一文理解Redux及其工作原理中...
    99+
    2022-11-13
  • 详解React项目中eslint使用百度风格
    1.安装百度Eslint Rule 插件 npm i -D eslint @babel/eslint-parser @babel/eslint-plugin @ecomfe/es...
    99+
    2022-11-12
  • 在 React 项目中全量使用 Hooks的方法
    目录前言React HooksuseStateuseReducer基础用法进阶用法useContextuseEffectuseLayoutEffectuseRefuseImperat...
    99+
    2022-11-13
    React使用 Hooks  React 项目使用 Hooks
  • 详解React Native项目中启用Hermes引擎
    目录引言一、启用 Hermes 引擎1.1 Android1.2 iOS二、Hermes 引擎使用2.1 检查 Hermes 引擎是否启用2.2 绑定Hermes2.3 使用DevT...
    99+
    2022-11-13
  • vue项目中使用ts(typescript)入门教程
    目录1、引入Typescript2、配置文件webpack配置3、让项目识别.ts4、vue组件的编写data()中定义数据props传值完整代码案例最近项目需要将原vue项目结合t...
    99+
    2022-11-12
  • React项目搭建与Echars工具使用详解
    目录一、React项目快速搭建1、新建文件夹2、直接在对应目录输入 cmd ,打开终端3、执行指令完成React应用建立二、React项目结构和分析1、删除多于文件,使得结构清晰2、...
    99+
    2023-03-20
    React使用Echars React Echars工具使用
  • 如何在React项目中优雅的使用对话框
    目录背景场景一场景二场景三问题一:难以扩展问题二:维护问题问题的本质对话框的本质全局的状态管理的对话框整体的架构具体实现Redux - reducer 存储Redux - actio...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作