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

React应用路由异常及API数据获取失败问题求助

Fixing Your React App's Routing and API Fetch Issues

Hey there! Let's work through your React app's problems step by step—we'll tackle routing first, then the API data fetching.

1. Routing Troubleshooting

Looking at your react-router-dom version (v5.3.0 in package.json), your original routing code is actually correct for v5. The issues might come from accidental mismatches when you tested switching to v6-style syntax (like using element instead of component). Here's what to confirm:

  • Don't use element prop: That's a React Router v6 feature. For v5, stick with the component prop on your Route components.
  • Keep Switch: Switch is necessary in v5 to ensure only the first matching route renders. Replacing it with just Route would break intended routing behavior even if you only have one route.
  • Verify root element: Make sure your public/index.html has a <div id="root"></div>—this is where your app mounts, and your index.js targets it correctly.

Your existing Routess.js should work fine if you revert any v6-style changes. Here's the correct v5 code again for reference:

import React from "react"
import {BrowserRouter, Switch, Route} from "react-router-dom";
import Home from "./core/Home";

const Routess = () => {
 return (
 <BrowserRouter>
 <Switch>
 <Route path="/" exact component={Home}/>
 </Switch>
 </BrowserRouter>
 );
};

export default Routess;

2. API Data Fetching Fixes

The biggest issue here is a useState destructuring mistake in your Home.js—plus some missing error handling in your fetch call. Let's fix these:

a. Fix useState Destructuring

You used object destructuring for useState, but useState returns an array, not an object. This caused products and setProducts to be undefined, so your state never updated.

Wrong:

const {products, setProducts} = useState([]);

Correct:

const [products, setProducts] = useState([]);

b. Fix API Request Path

In coreapicall.js, your API path is missing a slash between API and product. This would lead to an invalid URL (e.g., if API is http://localhost:5000/api/, you'd get http://localhost:5000/apiproduct instead of http://localhost:5000/api/product).

Corrected coreapicall.js:

import {API} from "../../backend";

export const getProducts = () => {
 return fetch(`${API}/product`, {method:"GET"})
 .then((response) => {
   // Add check for HTTP errors (fetch only catches network errors)
   if (!response.ok) {
     throw new Error(`HTTP error! Status: ${response.status}`);
   }
   return response.json();
 })
 .catch((err) => {
   console.log("Fetch error:", err);
   return { error: err.message }; // Return error object for component to handle
 });
};

c. Update Home.js Error Logging & Loading State

When you log error right after setError(data.error), the state hasn't updated yet (since setError is asynchronous). Log data.error directly instead, and add a loading state to handle empty product lists gracefully:

Updated Home.js:

import React, {useState, useEffect} from 'react'
import {getProducts} from "./helper/coreapicalls"

export default function Home() {
 // Fixed array destructuring
 const [products, setProducts] = useState([]);
 const [error, setError] = useState(false);

 const loadAllProducts = () => {
 getProducts()
 .then((data) => {
   if (data.error){
     setError(data.error)
     console.log("API Error:", data.error); // Log the actual error from API response
   } else {
     setProducts(data);
   }
 });
 };

 useEffect(() => {
 loadAllProducts();
 }, []);

 return (
 <div>
 <h1>Home Component </h1>
 <div className="row">
 {products.length === 0 ? (
   <p>No products found, or still loading...</p>
 ) : (
   products.map((product, index) => {
     return(
     <div key={index}>
     <h1>{product.name}</h1>
     </div>
     );
   })
 )}
 </div>
 </div>
 );
}

3. Debugging Tips

  • Open your browser's DevTools Console to check for any syntax errors or warnings.
  • Go to the Network tab in DevTools to see if the API request is being sent, and check the request URL, status code, and response data.
  • Verify that your backend API is running and accessible at the API path you defined.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 09:04:04