react-slingshot 与 GraphQL 集成:Apollo Client 使用指南

【免费下载链接】react-slingshot React + Redux starter kit / boilerplate with Babel, hot reloading, testing, linting and a working example app built in 【免费下载链接】react-slingshot 项目地址: https://gitcode.com/gh_mirrors/re/react-slingshot

你是否正在使用 react-slingshot 开发应用,但苦于 REST API 数据获取的繁琐?是否希望用更高效的方式管理前端数据?本文将带你一步步实现 react-slingshot 与 GraphQL 的无缝集成,通过 Apollo Client 轻松搞定数据获取、缓存和状态管理。读完本文后,你将能够:掌握 Apollo Client 在 react-slingshot 中的配置方法、学会编写和执行 GraphQL 查询、理解如何处理数据缓存与状态管理。

环境准备与依赖安装

react-slingshot 作为 React + Redux 开发脚手架,本身并不包含 GraphQL 相关依赖。我们需要先安装 Apollo Client 及相关依赖。由于项目使用 React 16.11.0,建议安装 Apollo Client 3.3.0 版本以确保兼容性:

npm install @apollo/client@3.3.0 graphql --legacy-peer-deps

安装完成后,可在 package.json 文件中查看依赖是否添加成功。关键依赖包括:@apollo/client(核心客户端库)、graphql(GraphQL 语法支持)。

Apollo Client 配置与 Redux 集成

react-slingshot 使用 Redux 进行状态管理,我们需要将 Apollo Client 与 Redux 结合,实现数据的统一管理。修改 src/store/configureStore.js 文件,添加 Apollo Client 中间件:

import { ApolloClient, InMemoryCache, ApolloProvider, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { ApolloLink } from '@apollo/client';

// 创建 HTTP 链接
const httpLink = createHttpLink({
  uri: 'https://api.example.com/graphql', // 替换为你的 GraphQL API 地址
});

// 添加认证头(如有需要)
const authLink = setContext((_, { headers }) => ({
  headers: {
    ...headers,
    authorization: `Bearer ${localStorage.getItem('token')}`,
  }
}));

// 创建 Apollo Client 实例
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

// 在 configureStoreProd 和 configureStoreDev 函数中添加 Apollo 中间件
const middlewares = [
  thunk,
  reactRouterMiddleware,
  // 添加 Apollo Client 中间件
  (store) => (next) => (action) => {
    // 可在此处添加 Redux 与 Apollo 的联动逻辑
    return next(action);
  }
];

上述配置中,我们创建了 Apollo Client 实例并配置了 GraphQL API 地址、认证头信息和缓存策略。同时,将 Apollo 中间件集成到了 Redux 的中间件链中,实现了 Redux 与 Apollo Client 的协同工作。

组件中使用 Apollo Client 获取数据

完成配置后,我们可以在 React 组件中使用 Apollo Client 获取数据。以 src/components/containers/FuelSavingsPage.js 为例,添加 GraphQL 查询功能:

import { useQuery, gql } from '@apollo/client';

// 定义 GraphQL 查询
const GET_FUEL_DATA = gql`
  query GetFuelData($vehicleType: String!) {
    fuelPrices(vehicleType: $vehicleType) {
      regular
      premium
      diesel
      updatedAt
    }
    vehicleEfficiency(vehicleType: $vehicleType) {
      cityMpg
      highwayMpg
      combinedMpg
    }
  }
`;

const FuelSavingsPage = () => {
  const [vehicleType, setVehicleType] = useState('sedan');
  
  // 使用 useQuery 钩子执行查询
  const { loading, error, data, refetch } = useQuery(GET_FUEL_DATA, {
    variables: { vehicleType },
  });

  if (loading) return <div>加载中...</div>;
  if (error) return <div>错误: {error.message}</div>;

  return (
    <div>
      <h2>燃油数据查询</h2>
      <select value={vehicleType} onChange={(e) => setVehicleType(e.target.value)}>
        <option value="sedan">轿车</option>
        <option value="suv">SUV</option>
        <option value="truck">卡车</option>
      </select>
      <button onClick={() => refetch()}>刷新数据</button>
      
      <div className="fuel-prices">
        <h3>当前燃油价格</h3>
        <p>普通汽油: {data.fuelPrices.regular} 元/升</p>
        <p>优质汽油: {data.fuelPrices.premium} 元/升</p>
        <p>柴油: {data.fuelPrices.diesel} 元/升</p>
        <p>更新时间: {new Date(data.fuelPrices.updatedAt).toLocaleString()}</p>
      </div>
      
      <div className="vehicle-efficiency">
        <h3>车辆燃油效率</h3>
        <p>城市路况: {data.vehicleEfficiency.cityMpg} MPG</p>
        <p>高速路况: {data.vehicleEfficiency.highwayMpg} MPG</p>
        <p>综合路况: {data.vehicleEfficiency.combinedMpg} MPG</p>
      </div>
    </div>
  );
};

在上述代码中,我们使用 gql 标签定义了 GraphQL 查询,然后通过 useQuery 钩子在组件中执行查询。useQuery 钩子返回了 loadingerrordatarefetch 等属性,分别用于处理加载状态、错误信息、查询结果和重新获取数据的功能。

数据缓存与状态管理

Apollo Client 内置了强大的缓存机制,可以自动管理查询结果的缓存。当我们再次执行相同的查询时,Apollo Client 会优先从缓存中获取数据,提高应用性能。如果需要手动更新缓存,可以使用 update 函数或 writeQuery 方法:

import { useMutation, gql } from '@apollo/client';

const UPDATE_VEHICLE_EFFICIENCY = gql`
  mutation UpdateVehicleEfficiency($input: VehicleEfficiencyInput!) {
    updateVehicleEfficiency(input: $input) {
      id
      cityMpg
      highwayMpg
      combinedMpg
    }
  }
`;

const VehicleEfficiencyForm = ({ vehicleId }) => {
  const [updateVehicleEfficiency] = useMutation(UPDATE_VEHICLE_EFFICIENCY, {
    update(cache, { data: { updateVehicleEfficiency } }) {
      // 更新缓存
      cache.writeQuery({
        query: GET_FUEL_DATA,
        variables: { vehicleType: 'sedan' },
        data: {
          // 更新缓存数据
          vehicleEfficiency: updateVehicleEfficiency
        }
      });
    }
  });
  
  // 表单提交处理
  const handleSubmit = (e) => {
    e.preventDefault();
    updateVehicleEfficiency({
      variables: {
        input: {
          id: vehicleId,
          cityMpg: 28,
          highwayMpg: 36,
          combinedMpg: 31
        }
      }
    });
  };
  
  return (
    <form onSubmit={handleSubmit}>
      {/* 表单内容 */}
      <button type="submit">更新燃油效率数据</button>
    </form>
  );
};

总结与最佳实践

通过本文的介绍,我们实现了 react-slingshot 与 GraphQL 的集成,使用 Apollo Client 进行数据获取和状态管理。以下是一些最佳实践:

  1. 合理规划查询结构:尽量减少请求次数,通过一个查询获取所需的所有数据。
  2. 利用缓存优化性能:充分利用 Apollo Client 的缓存机制,减少网络请求。
  3. 错误处理与加载状态:始终处理加载状态和错误情况,提升用户体验。
  4. 认证与安全:通过 Apollo Link 添加认证头,确保 API 访问安全。
  5. 与 Redux 协同工作:对于复杂状态管理,可结合 Redux 和 Apollo Client,各司其职。

通过这些步骤,你可以在 react-slingshot 项目中充分利用 GraphQL 和 Apollo Client 的优势,构建高效、灵活的前端应用。更多高级用法,请参考 Apollo Client 官方文档

【免费下载链接】react-slingshot React + Redux starter kit / boilerplate with Babel, hot reloading, testing, linting and a working example app built in 【免费下载链接】react-slingshot 项目地址: https://gitcode.com/gh_mirrors/re/react-slingshot

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐