Sanity.io + React Native Expo:TypeError: undefined is not a function问题求助
解决React Native Expo中Sanity客户端TypeError: undefined is not a function错误
问题根源
你在Homescreen.js里错误导入了createClient,但你的sanity.js文件并没有导出这个方法——你导出的是已经初始化完成的client实例(同时做了命名导出和默认导出),而非createClient函数。当你尝试调用createClient.fetch()时,createClient是undefined,自然触发"undefined is not a function"错误。
修复方案
修改Homescreen.js中的导入语句,改用正确方式导入client实例:
方式1:导入命名导出的client
// Homescreen.js import { client } from "../sanity";
方式2:导入默认导出的client
// Homescreen.js import client from "../sanity";
之后正常调用client.fetch()即可,示例:
client.fetch('*[_type == "yourDocumentType"]') .then(data => console.log(data)) .catch(err => console.error(err));
额外排查点
- 确认
@sanity/client版本与视频中Sonny使用的版本一致(版本差异可能导致API变化),可执行npm list @sanity/client查看当前版本,若不一致则安装对应版本:npm install @sanity/client@x.x.x - 确保Sanity令牌能被正确读取,React Native Expo中环境变量需通过
expo-constants读取,可调整sanity.js:import { createClient } from "@sanity/client"; import Constants from 'expo-constants'; export const client = createClient({ projectId: 'myprojectID', dataset: 'production', apiVersion: '2023-03-05', useCdn: true, token: Constants.expoConfig.extra.TOKEN, // 需在app.json的extra字段配置令牌 }) export default client;
内容的提问来源于stack exchange,提问作者Adam Terhaerdt
相关产品推荐
相关产品推荐

