React使用笔记(持续更新中)

文件结构:

根目录(项目名)

|-config

|-config.jsx

|-src

|-taskpane

|-components

|-Login.jsx

|-taskpane.html

|-taskpane.jsx

|-index.jsx

|-until

|-common.jsx

until/common.jsx代码:

bash 复制代码
// utils/request.js
import { API_BASE_URL } from "@config/config";
// 封装 fetch
export async function request(url,options = {},token="") {
  const finalUrl = API_BASE_URL + url;
  let defaultOptions=false;
  if(token){
    defaultOptions = {
      headers: {
        "Content-Type": "application/json",
        'Authorization': `Bearer ${token}`,
      },
      mode: 'cors',  // 确保是 CORS 模式
      ...options,
    };
  }else{
    defaultOptions = {
      headers: {
        "Content-Type": "application/json",
      },
      mode: 'cors',  // 确保是 CORS 模式
      ...options,
    };
  }
  

  try {
    const res = await fetch(finalUrl, defaultOptions);

    if (!res.ok) {
      throw new Error(`请求失败: ${res.status} ${res.statusText}`);
    }

    // 自动解析 JSON
    const data = await res.json();
    return data;
  } catch (err) {
    console.error("请求错误:", err);
    throw err;
  }
}

// 便捷方法:GET
export function get(url,params=false,token="") {
  let queryString = "";
  if (params) {
    const searchParams = new URLSearchParams();
    params.forEach((item, index) => {
      searchParams.append(index, item);
    });
    queryString = `?${searchParams.toString()}`;
  }
  return request(url + queryString, { method: "GET" },token);
}

// 便捷方法:POST
export async function post(url, params,token="") {
  return request(url, {
    method: "POST",
    body: JSON.stringify(params),
  },token);
}

config/config.jsx代码:

bash 复制代码
export const API_BASE_URL = "http://localhost";
export const API_URL = {
    Edit_Url:"/index/meal/dataupdate",
    Login_Url:"/index/meal/mlwlogin",
}

一、如果要在对应文件中引用非同级的文件

例如:index.jsx中需要应用Login.jsx、until/common.jsx和config/config.jsx。引用Login.jsx文件可以直接./components/Logins.jsx。但是使用until/common.jsx和config/config.jsx就有两种方式。

bash 复制代码
import * as React from "react";
import Login from "./components/Login";
import { API_URL } from "@config/config";
import {post} from "@utils/common";

const rootElementLogin = document.getElementById("container");
const rootLogin = rootElementLogin ? createRoot(rootElementLogin) : undefined;

async function greetUser() {
    let params={
        userid:123
    };
    const result = await post(API_URL.Edit_Url, params);
    return <div>
                <div>123</div>
                <Login></Login>
            </div>;
}

第一种:无需作配置,直接使用

bash 复制代码
import {API_URL} from "../../config/config.jsx";
import {post} from "../../until/commont.jsx";

第二种:需要做配置,可以直接使用定义的内容应用

bash 复制代码
import { API_URL } from "@config/config";
import {post} from "@utils/common";

配置内容:

bash 复制代码
//在tsconfig.json中加入配置
{
  "compilerOptions": {
    //配置根目录
    "baseUrl": ".",
    "paths": {
      "@config/*": ["config/*"],
      "@utils/*": ["utils/*"]
    }
},
  //配置根目录
  "include": ["config", "utils"]
}
//项目类型,配置构建工具。一般就两种vite.config.ts或者webpack.config.js
//webpack.config.js:
const path = require("path");
module.exports = async (env, options) => {
    resolve: {
      alias: {
        "@config": path.resolve(__dirname, "config"),
        "@utils": path.resolve(__dirname, "utils")
      },
    },
});


//vite.config.ts:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@config': path.resolve(__dirname, './config'),
      '@utils': path.resolve(__dirname, './utils')
    }
  }
})
相关推荐
counterxing1 小时前
我整理了一个免费开发资源目录,还做成了 CLI 和 MCP
前端·agent·ai编程
子兮曰8 小时前
Bun v1.3.14 深度解析:Image API、HTTP/3、全局虚拟存储与五十项变革
前端·后端·bun
kyriewen9 小时前
今天,百年巨头一次砍了9200人,而一个离职科学家的实话让全网睡不着觉
前端·openai·ai编程
问心无愧05139 小时前
ctf show web 入门42
android·前端·android studio
kyriewen10 小时前
老板逼我上AI,我偷偷在浏览器里跑LLaMA,省下20万API费
前端·react.js·llm
Beginner x_u10 小时前
前端八股整理(手写 02)|数组转树、数组扁平化、随机打乱一个数组
前端·数组·数组转树·数组扁平化
KaMeidebaby10 小时前
卡梅德生物技术快报|禽类成纤维细胞 FISH 实验:鸟类性别染色体基因定位技术实现与数据验证
前端·数据库·其他·百度·新浪微博
天若有情67310 小时前
前端高阶性能优化:跳出传统懒加载与预加载,基于用户行为做轻量预判加载
前端·性能优化
小小小小宇10 小时前
前端转后端:SQL 是什么
前端
张元清11 小时前
React Observer Hooks:7 种监听 DOM 而不写样板代码的方式
前端·javascript·面试