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

MERN Stack项目中服务器获取数据无法在前端展示问题求助(仿亚马逊电商网站开发)

Troubleshooting: Product Data Not Displaying in ProductScreen (MERN + Redux)

It sounds like you've already done solid initial debugging—confirming data exists in the Redux store but isn't showing up in your component's product variable is a key clue. Let's break down the most likely issues and how to fix them step by step:

1. Check Your productDetailsReducer Implementation

The first critical spot to inspect is your productDetailsReducer (you didn't include this code, but it's the bridge between your action and component state). It needs to correctly initialize and update the product field in the state slice.

Correct Reducer Example

Make sure your reducer follows this pattern:

// reducers/productReducers.js
import { PRODUCT_DETAILS_REQUEST, PRODUCT_DETAILS_SUCCESS, PRODUCT_DETAILS_FAIL } from '../constants/productConstants';

export const productDetailsReducer = (state = { loading: true, product: {} }, action) => {
  switch (action.type) {
    case PRODUCT_DETAILS_REQUEST:
      return { ...state, loading: true };
    case PRODUCT_DETAILS_SUCCESS:
      // Ensure we assign the full product object from the action payload
      return { loading: false, product: action.payload };
    case PRODUCT_DETAILS_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
};

Common Mistakes: Forgetting to spread the existing state (...state) in the request case, or assigning the payload to the wrong field (e.g., products instead of product).

2. Verify the detailsProduct Action Logic

Next, confirm your action is fetching the right data and dispatching the success action with a valid payload.

Correct Action Example

Ensure your API request returns a single product object, and you're passing that object to the reducer:

// actions/productActions.js
import axios from 'axios';
import { PRODUCT_DETAILS_REQUEST, PRODUCT_DETAILS_SUCCESS, PRODUCT_DETAILS_FAIL } from '../constants/productConstants';

export const detailsProduct = (productId) => async (dispatch) => {
  try {
    dispatch({ type: PRODUCT_DETAILS_REQUEST });
    // Double-check the API endpoint matches your Express route
    const { data } = await axios.get(`/api/products/${productId}`);
    // Dispatch the full product data as the payload
    dispatch({ type: PRODUCT_DETAILS_SUCCESS, payload: data });
  } catch (error) {
    dispatch({
      type: PRODUCT_DETAILS_FAIL,
      payload: error.response?.data?.message || error.message,
    });
  }
};

Common Mistake: If your API returns data nested under a field like data.product, you need to pass data.product as the payload instead of just data.

3. Confirm Route Parameter Matching

Make sure your route definition uses the same parameter name as your component expects. In your ProductScreen, you're grabbing props.match.params.id—check your route setup:

// Example in App.js/Routes.js
import { Route } from 'react-router-dom';
import ProductScreen from './screens/ProductScreen';

// Route must use :id to match your component's param
<Route path="/product/:id" component={ProductScreen} />

Common Mistake: Using a different parameter name like :productId would make props.match.params.id undefined, leading to a failed API request.

4. Debug Component State and Redux Store

Add targeted logs to see exactly what's happening in your component:

export default function ProductScreen(props) {
  const dispatch = useDispatch();
  const productId = props.match.params.id;
  const [qty, setQty] = useState(1);
  const productDetails = useSelector((state) => state.productDetails);
  const { loading, error, product } = productDetails;

  // Add these logs to debug state and route params
  console.log('Full Product Details State:', productDetails);
  console.log('Product ID from Route:', productId);

  useEffect(() => {
    dispatch(detailsProduct(productId));
  }, [dispatch, productId]);

  // ... rest of your component
}

Also use Redux DevTools to:

  • Watch the PRODUCT_DETAILS_SUCCESS action and verify the payload is a valid product object with fields like name, price, etc.
  • Check if the productDetails state updates correctly after the action is dispatched.

5. Ensure Your API Returns Valid Data

Test your Express API endpoint directly (e.g., with Postman or curl) to confirm it returns a single product object:

curl http://localhost:5000/api/products/your-product-id

If the response is empty or missing required fields, the issue lies in your backend route or MongoDB query, not your frontend/Redux code.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:47:40