当前位置:首页 > React

react如何在model层写函数调接口

2026-01-26 07:51:40React

React 中 Model 层函数调用接口的实现

在 React 应用中,Model 层通常负责数据管理和接口调用。可以通过以下方式组织代码:

创建独立的 API 服务模块

将接口调用封装在单独的 service 文件中,例如 apiService.js

react如何在model层写函数调接口

import axios from 'axios';

const BASE_URL = 'https://api.example.com';

export const fetchUserData = async (userId) => {
  try {
    const response = await axios.get(`${BASE_URL}/users/${userId}`);
    return response.data;
  } catch (error) {
    console.error('Error fetching user data:', error);
    throw error;
  }
};

export const updateUserData = async (userId, data) => {
  try {
    const response = await axios.put(`${BASE_URL}/users/${userId}`, data);
    return response.data;
  } catch (error) {
    console.error('Error updating user data:', error);
    throw error;
  }
};

使用自定义 Hook 封装业务逻辑

创建自定义 Hook 来组合多个接口调用:

react如何在model层写函数调接口

import { useState, useEffect } from 'react';
import { fetchUserData, updateUserData } from './apiService';

export const useUserModel = (userId) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const loadUser = async () => {
    setLoading(true);
    try {
      const data = await fetchUserData(userId);
      setUser(data);
    } catch (err) {
      setError(err);
    } finally {
      setLoading(false);
    }
  };

  const saveUser = async (userData) => {
    setLoading(true);
    try {
      const updatedUser = await updateUserData(userId, userData);
      setUser(updatedUser);
    } catch (err) {
      setError(err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadUser();
  }, [userId]);

  return { user, loading, error, saveUser };
};

在组件中使用 Model 层

组件只需调用 Hook 而不需关心具体实现:

import { useUserModel } from './models/useUserModel';

function UserProfile({ userId }) {
  const { user, loading, error, saveUser } = useUserModel(userId);

  const handleSave = async (formData) => {
    try {
      await saveUser(formData);
      // 处理保存成功后的逻辑
    } catch (err) {
      // 处理错误
    }
  };

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {/* 渲染用户界面 */}
    </div>
  );
}

使用状态管理工具集成

如果需要全局状态管理,可以将 Model 层与 Redux 或 Context API 结合:

// 在 Redux 的 async thunk 中调用接口
export const fetchUser = createAsyncThunk(
  'user/fetch',
  async (userId, { rejectWithValue }) => {
    try {
      return await fetchUserData(userId);
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

// 在 slice 中处理状态
const userSlice = createSlice({
  name: 'user',
  initialState: { data: null, loading: false, error: null },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchUser.pending, (state) => {
        state.loading = true;
      })
      .addCase(fetchUser.fulfilled, (state, action) => {
        state.data = action.payload;
        state.loading = false;
      })
      .addCase(fetchUser.rejected, (state, action) => {
        state.error = action.payload;
        state.loading = false;
      });
  }
});

最佳实践建议

  • 保持 Model 层纯粹,只关注数据逻辑
  • 使用 TypeScript 定义接口返回类型
  • 添加请求拦截器和响应拦截器处理通用逻辑
  • 考虑使用 React Query 等数据获取库简化流程
  • 对敏感操作添加权限校验层

标签: 函数接口
分享给朋友:

相关文章

uniapp如何写全局函数

uniapp如何写全局函数

全局函数的定义与使用 在UniApp中定义全局函数可以通过挂载到Vue.prototype或使用模块化导出导入的方式实现。以下是两种常用方法: 方法一:挂载到Vue.prototype 在main.…

java如何写接口

java如何写接口

定义接口 在Java中,使用interface关键字定义接口。接口可以包含抽象方法、默认方法、静态方法和常量(隐式为public static final)。 public interface…

react如何使用函数

react如何使用函数

使用函数组件的基本语法 在React中,函数组件是通过JavaScript函数定义的组件。函数接收props作为参数,并返回React元素。 function Welcome(props) {…

vue中实现接口

vue中实现接口

Vue 中实现接口调用的方法 在 Vue 中实现接口调用通常使用 axios 或 fetch 等 HTTP 客户端库。以下是常见的实现方式: 安装 axios 通过 npm 或 yarn 安装 ax…

vue 实现接口调用

vue 实现接口调用

使用 Axios 进行接口调用 安装 Axios 依赖: npm install axios 在 Vue 组件中引入并使用: import axios from 'axios'; expor…

vue实现接口配置

vue实现接口配置

Vue 中实现接口配置的方法 在 Vue 项目中配置接口通常涉及以下几个关键步骤: 创建 API 配置文件 新建一个 api 目录,创建 index.js 文件作为接口配置入口。可以将接口按模块分类…