React Native 中 Context 数据加载状态判断的正确写法

1次阅读

React Native 中 Context 数据加载状态判断的正确写法

react Native 中使用 Context 管理 API 数据时,需准确判断初始加载状态:details 初始值为 NULL(非 undefined),直接用 details !== undefined 会导致条件失效,引发 Cannot read Property ‘adult’ of null 等运行时错误。

react native 中使用 context 管理 api 数据时,需准确判断初始加载状态:`details` 初始值为 `null`(非 `undefined`),直接用 `details !== undefined` 会导致条件失效,引发 `cannot read property ‘adult’ of null` 等运行时错误。

react native 应用中,通过 Context 提供异步获取的 API 数据(如电影列表)是一种常见模式。但一个极易被忽略的关键点是:初始状态的语义必须与实际初始化值严格一致

在你的 CallApiProvider 中,useState(null) 明确将 details 初始化为 null:

const [details, setDetails] = useState(null); // 注意:这里是 null,不是 undefined

而你在 Search 组件中却用以下逻辑判断加载状态:

if (details !== undefined) { /* 渲染主界面 */ } else { /* 渲染 Loading */ }

这会导致严重问题:当 details 为 null 时,null !== undefined 返回 true,条件体仍会执行,进而尝试访问 details.adult 或遍历 details(此时为 null),最终抛出 TypeError: Cannot read property ‘adult’ of null —— 这正是你遇到的错误根源。

✅ 正确的加载状态判断方式有以下几种(推荐按优先级选择):

  • 最简洁可靠(推荐):直接使用真值判断(null、undefined、false、0、” 均为 falsy)

    if (details) {   // 数据已就绪,安全渲染   return (     <ScrollView style={styles.container}>       <Busca dica="Type title, categories, years, etc" />       <FlatList         data={details}         renderItem={({ item }) => <EnviromentButton title={item.id} active />}         horizontal         showsHorizontalScrollIndicator={false}         contentContainerStyle={styles.genreList}       />       {/* 其他组件... */}     </ScrollView>   ); } else {   // 数据未加载或为空,显示加载指示器   return (     <ScrollView style={styles.container}>       <ActivityIndicator size="large" color="#6200ee" />     </ScrollView>   ); }
  • 显式比较 null(语义清晰,适合强调“空数据”而非“未定义”):

    if (details !== null) { ... }
  • 兼顾 null 和 undefined 的防御性写法(较少必要,但更严谨):

    if (details != null) { ... } // 使用抽象相等,可同时排除 null 和 undefined

⚠️ 注意事项:

  • 不要依赖 typeof details === ‘undefined’ 或 details !== undefined,除非你明确初始化为 undefined(例如 useState() 不传参),但本例中是 useState(null),二者语义不同;
  • useContext(ApiContext) 返回的是 Context 的当前值,它不会自动“等待”异步完成——状态判断必须由消费者组件(如 Search)主动承担;
  • 若后续需支持错误重试或空数据提示,建议将状态升级为 { data: null | T[], loading: Boolean, error: String | null } 形式,避免仅靠 null/falsy 值承载多重含义。

总结:状态判断必须与 useState 的初始值严格对齐。null ≠ undefined,这是 JavaScript 的基础特性,也是 React 数据流健壮性的第一道防线。修正判断逻辑后,加载流程将按预期工作:先显示 ActivityIndicator,待 details 赋值为数组后再渲染完整 ui

text=ZqhQzanResources