ReactJS调用指定API无数据返回且无报错,求技术帮助
Hey there! Let's figure out why your fetch call isn't returning data and isn't throwing any errors. Here are practical troubleshooting steps and fixes to try out:
1. Add Error Handling (The Most Critical First Step)
Your current code doesn't handle errors properly—fetch only rejects when there's a total network failure (like being offline). HTTP errors (404, 500, etc.) won't trigger a catch by default, which is why you're seeing no feedback. Let's add error catching and response validation:
Update your componentDidMount method:
componentDidMount() { fetch("https://facebook.github.io/react-native/movies.json") .then(response => { // First check if the response is successful if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(findresponse => { console.log("Fetched full data:", findresponse); // Log to verify structure this.setState({ data: findresponse.movies }); }) .catch(error => { console.error("Fetch failed:", error); // This will catch all errors now }); }
This will show you exactly what's wrong—whether it's a network issue, invalid response, or data structure mismatch—in your browser's console.
2. Verify the Data Structure
Use the console.log(findresponse) we added to confirm the API returns the structure you expect. While the official React Native sample does have a movies array, it's always good to double-check (e.g., maybe the field name is films instead? Unlikely here, but possible with other APIs).
3. Add Loading/Empty States for Better Feedback
Your initial state sets data: [], so the component renders nothing if fetch fails or takes time. Let's add loading and error states to make this clearer:
constructor() { super(); // Add loading and error to state this.state = { data: [], loading: true, error: null }; } componentDidMount() { fetch("https://facebook.github.io/react-native/movies.json") .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(findresponse => { this.setState({ data: findresponse.movies, loading: false }); }) .catch(error => { this.setState({ error: error.message, loading: false }); console.error("Fetch failed:", error); }); } render() { const { data, loading, error } = this.state; if (loading) return <div>Loading movies...</div>; if (error) return <div>Oops! {error}</div>; return ( <div> {data.length === 0 ? ( <div>No movies found</div> ) : ( data.map((dynamicData, key) => ( <div key={key}> {/* Don't forget the key prop for React lists! */} <span>{dynamicData.title}</span> - <span>{dynamicData.releaseYear}</span> </div> )) )} </div> ); }
Also, note that adding a key prop to list items is required by React to avoid warnings and ensure proper re-rendering.
4. Check Network Requests in Dev Tools
Open your browser's developer tools (F12), go to the Network tab, then refresh the page. Look for the fetch request to movies.json:
- Did the request even send?
- Is the response status code 200 (success)?
- Can you see the correct JSON data in the Preview tab?
CORS issues are rare here (GitHub Pages allows cross-origin requests), but this will confirm if the API is reachable.
5. Confirm Fetch Support
If you're working in an older browser or niche environment, fetch might not be supported. You can switch to axios or XMLHttpRequest as an alternative, but modern browsers and React Native environments should support fetch out of the box.
Start with adding error handling first—it will point you directly to the root cause!
内容的提问来源于stack exchange,提问作者dina omari

