React Native中Firebase按指定cat字段筛选读取数据失败求助
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
setstateis actuallysetState(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

