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

React Native接入Sanity后端iOS端报URLSearchParams.set未实现错误

React Native iOS端调用Sanity API报错URLSearchParams.set is not implemented

问题场景

在React Native项目中通过Sanity客户端拉取数据时,Web端正常运行,但iOS端抛出错误:URLSearchParams.set is not implemented。相关代码如下:

数据获取组件代码

import {View, Text,SafeAreaView,Image,TextInput,ScrollView} from 'react-native'
import React, {useEffect, useLayoutEffect, useState} from 'react'
import {useNavigation} from "@react-navigation/native";
import {ChevronDownIcon, UserIcon,AdjustmentsVerticalIcon,MagnifyingGlassIcon} from "react-native-heroicons/outline";
import Categories from "../components/Categories";
import FeaturedRow from "../components/FeaturedRow";
import client from "../sanity";

const HomeScreen = () => {
    const navigation = useNavigation();
    const [featuredItems, setFeaturedItems] = useState([]);

    useLayoutEffect(()=>{
        navigation.setOptions({
            headerShown: false,
        });
    },[]);

    useEffect(()=>{
        const query = `*[_type == "featured"]`;

        client
            .fetch(query)
            .then((data)=>{
                setFeaturedItems(data)
            })
            .catch((error)=>{
                console.log('Error:',error);
            });
    }, []);
    // 省略其余组件渲染代码
}

Sanity客户端配置代码

import sanityClient, {createClient} from '@sanity/client'
import imageURLBuilder from '@sanity/image-url'

const client = sanityClient({
    projectId: "9hrg98uk",
    dataset: "production",
    useCdn: true,
    apiVersion: "2021-10-21",
});

const builder = imageURLBuilder(client);
export const urlFor = (source) => builder.image(source);

export default client;

原因分析

React Native的iOS环境中,URLSearchParams的部分方法(如set)未被完整实现,而旧版本的Sanity客户端依赖了这些未实现的方法,导致兼容性报错。

解决方案

方案1:升级Sanity客户端并规范实例创建

较新版本的@sanity/client已修复React Native环境兼容问题,先执行升级命令:

npm install @sanity/client@latest
# 或使用yarn
yarn add @sanity/client@latest

然后修改客户端配置代码,改用官方推荐的createClient创建实例:

import {createClient} from '@sanity/client'
import imageURLBuilder from '@sanity/image-url'

const client = createClient({
    projectId: "9hrg98uk",
    dataset: "production",
    useCdn: true,
    apiVersion: "2021-10-21",
});

const builder = imageURLBuilder(client);
export const urlFor = (source) => builder.image(source);

export default client;

方案2:添加URLSearchParams Polyfill

若暂时无法升级依赖,可在项目入口文件(如App.js或index.js)顶部添加Polyfill:

import 'react-native-url-polyfill/auto';

先安装对应依赖包:

npm install react-native-url-polyfill
# 或使用yarn
yarn add react-native-url-polyfill

方案3:临时禁用Sanity CDN(不推荐生产环境)

修改客户端配置,关闭CDN使用:

const client = createClient({
    // ...其他配置项
    useCdn: false,
});

验证

修改完成后重新运行iOS项目,检查数据拉取是否正常,错误是否消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:35:14