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

React根据ID匹配并映射生成Div组件无内容显示问题求助

Fix: Console Logs Work But No Content Renders on Page

Got it, let's walk through why your code logs correctly but doesn't show anything on the page, and fix it up:

Key Issues in Your Code

  1. No Return Value from the Function
    Your getServicesDetails function runs map to create <div> elements, but it never returns those elements to the component that's supposed to render them. React (I'm assuming you're using React since you're writing JSX) can't render what it doesn't receive.

  2. Incorrect Loop Condition
    i <= length will cause i to reach ServicesDetails.length (which is 3 in your case), and trying to access ServicesDetails[3] will give you undefined (since array indexes start at 0). This is a silent error that breaks your logic.

  3. Uncaptured Map Result
    Even when your if condition matches, you run map but don't save or return its output. The console.log works because the loop executes, but the JSX elements are discarded immediately.

Fixed Code

const ServicesDetails = [ ["text1", "text2", "text3"], ["text5", "text6", "text7"], ["text8", "text9", "text10"] ];
const getServicesDetails = (prop) => {
  const index = parseInt(prop);
  // Validate the index to avoid out-of-bounds errors
  if (index >= 0 && index < ServicesDetails.length) {
    // Return the array of JSX elements created by map
    return ServicesDetails[index].map( (item, e) => {
      console.log(item, e);
      return <div key={e}>{item}</div>;
    });
  }
  // Return null if the index is invalid to avoid rendering errors
  return null;
};

What Changed

  • Added Validation: We check if the parsed index is within the valid range of the array to prevent accessing undefined.
  • Removed Unnecessary Loop: Instead of looping through every index, we directly access the subarray using the parsed prop value—this is more efficient and cleaner.
  • Returned the JSX: The map result is now returned from the function, so your component can receive and render the <div> elements.
  • Handled Invalid Cases: If the input prop doesn't match a valid index, we return null to avoid rendering issues.

Now when you call getServicesDetails with a valid prop (like "0", "1", or "2"), it will return the corresponding array of <div> elements, which will render on the page just like your console logs show.

内容的提问来源于stack exchange,提问作者Michał Warakomski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:23:13