You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Mobx结合函数式组件从服务器获取数据

Mobx + React函数式组件:fetch API数据展示示例

步骤1:安装依赖

先安装Mobx核心包和适配函数式组件的轻量绑定库:

npm install mobx mobx-react-lite
# 或使用yarn
yarn add mobx mobx-react-lite

步骤2:创建Mobx Store

定义一个Store类管理数据状态、加载状态、错误状态,以及API请求逻辑:

import { makeAutoObservable } from "mobx";

class CategoryStore {
  category = null;
  isLoading = false;
  error = null;

  constructor() {
    // 自动将属性设为可观察、方法设为可执行
    makeAutoObservable(this);
  }

  async fetchCategory() {
    this.isLoading = true;
    this.error = null;
    try {
      const response = await fetch("https://jservice.io/api/category?id=150");
      if (!response.ok) throw new Error(`请求失败:${response.status}`);
      this.category = await response.json();
    } catch (err) {
      this.error = err.message;
    } finally {
      this.isLoading = false;
    }
  }
}

// 创建全局Store实例
export const categoryStore = new CategoryStore();

步骤3:编写React函数式组件

用observer包裹组件,让它能响应Mobx状态变化,同时调用Store方法获取并渲染数据:

import React, { useEffect } from "react";
import { observer } from "mobx-react-lite";
import { categoryStore } from "./CategoryStore";

const CategoryDisplay = observer(() => {
  const { category, isLoading, error, fetchCategory } = categoryStore;

  // 组件挂载时发起API请求
  useEffect(() => {
    fetchCategory();
  }, []);

  if (isLoading) return <div>加载中...</div>;
  if (error) return <div>出错了:{error}</div>;
  if (!category) return null;

  return (
    <div style={{ padding: "20px" }}>
      <h2>{category.title}</h2>
      <p>分类ID:{category.id}</p>
      <p>题目总数:{category.clues_count}</p>
      <h3>题目列表</h3>
      <ul>
        {category.clues.map(clue => (
          <li key={clue.id} style={{ margin: "10px 0" }}>
            <strong>分值:{clue.value || "无"}</strong>
            <br />
            问题:{clue.question}
            <br />
            <em>答案:{clue.answer}</em>
          </li>
        ))}
      </ul>
    </div>
  );
});

export default CategoryDisplay;

步骤4:在应用中挂载组件

将组件导入并渲染到主应用中:

import React from "react";
import CategoryDisplay from "./CategoryDisplay";

function App() {
  return (
    <div className="App">
      <h1>Mobx API请求演示</h1>
      <CategoryDisplay />
    </div>
  );
}

export default App;

内容的提问来源于stack exchange,提问作者Synchro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 16:15:43