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

React Native中Firebase按指定cat字段筛选读取数据失败求助

Fixing Your Firebase Query for 'health' Category Data

Hey there! Let's sort out why your current Firebase query isn't returning the 'health' infographics you're after. I spot a couple of key issues with your approach, and we'll fix them step by step.

What's Wrong with the Current Query?

Your current URL uses startAt="d" and endAt="e" to filter results. But the 'health' category starts with an h, which falls way outside the d-e range—so no wonder you're getting no results! Plus, the way quotes are used in the URL might be causing unexpected behavior.

Step-by-Step Fixes

1. Use equalTo for Exact Matches

Since you want all entries where cat is exactly 'health', replace startAt and endAt with equalTo. This is the right tool for precise value matching.

2. Clean Up URL Parameters

Firebase Realtime Database's query parameters don't need extra double quotes around field names (like cat). For the value, you can keep the quotes to ensure it's treated as a string.

3. Optimize Code & Add Error Handling

We'll simplify the data transformation with Object.values() and add error handling to catch network issues or empty results.

Modified Working Code

const fetchData = async () => { 
  try {
    // Updated query to match 'health' exactly
    const req = await fetch( 
      'https://stratic-research-institute.firebaseio.com/infographics.json?orderBy=cat&equalTo="health"' 
    ); 
    const res = await req.json(); 

    // Handle empty result case
    if (!res) {
      setstate({ info: [], loading: false });
      return;
    }

    // Convert object values to array and reverse
    const loadedData = Object.values(res).reverse();
    setstate({ info: loadedData, loading: false }); 
  } catch (error) {
    console.error('Failed to fetch data:', error);
    setstate({ info: [], loading: false });
  }
};

Critical Extra Step: Ensure Indexes Are Set

Firebase requires indexes for ordered queries to work correctly. Go to your Firebase Console > Realtime Database > Rules, and add an index for the cat field:

{
  "rules": {
    "infographics": {
      ".indexOn": "cat"
    }
  }
}

Without this index, your query might fail silently or return incomplete results, especially as your dataset grows.

Quick Notes

  • Double-check that your setstate is actually setState (React uses camelCase for state setters—this might be a typo!)
  • The reverse() call will flip the order of your results; remove it if you want the default Firebase order.

内容的提问来源于stack exchange,提问作者Muhammad Faisal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:57:34