React Native Expo集成Sanity报错:TypeError: undefined is not an object
解决React Native Expo + Sanity CMS的
TypeError: undefined is not an object (evaluating '_sanity.default.fetch')错误 下面是针对报错的具体修复步骤:
1. 修正导入方式不匹配的问题
你的sanity.js文件中使用命名导出定义了sanityClient,但在HomeScreen.js里用了默认导入的方式,导致导入的sanityClient是undefined,因此调用fetch时会触发错误。
修改HomeScreen.js的导入语句:
// 把原来的默认导入改成命名导入 import { sanityClient } from '../sanity';
2. 修复imageUrlBuilder的参数错误
sanity.js中初始化图片URL构建器时,传入的是client(从@sanity/client导入的构造函数),而不是我们已经配置好的sanityClient实例,这会导致构建器无法正常工作,也可能影响客户端的初始化逻辑。
更新sanity.js的代码:
import client from '@sanity/client'; import imageUrlBuilder from '@sanity/image-url'; export const sanityClient = client({ projectId: '2hjc0jso', dataset: 'production', useCdn: true, apiVersion: '2021-10-21', }); // 传入配置好的sanityClient实例,而非原始构造函数 const builder = imageUrlBuilder(sanityClient); export const urlFor = (source) => builder.image(source);
3. 修正状态更新的变量名错误
HomeScreen.js的useEffect回调里,误将结果变量名写成了date,但实际获取到的结果是result,这会导致状态无法正确更新。
修复useEffect中的状态更新代码:
useEffect(() => { sanityClient.fetch('*[_type == "featured"] {...,restaurants[] -> {...,dishes[]->, } }') .then((result) => { setFeaturedCategories(result); // 将date改为result }).catch((err) => { console.log(err); }); }, []);
完成以上三步修改后,重新运行项目,应该就能正常从Sanity CMS获取数据了。
内容的提问来源于stack exchange,提问作者Mariyan Anjelo
相关产品推荐
相关产品推荐

