React根据ID匹配并映射生成Div组件无内容显示问题求助
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
No Return Value from the Function
YourgetServicesDetailsfunction runsmapto 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.Incorrect Loop Condition
i <= lengthwill causeito reachServicesDetails.length(which is 3 in your case), and trying to accessServicesDetails[3]will give youundefined(since array indexes start at 0). This is a silent error that breaks your logic.Uncaptured Map Result
Even when yourifcondition matches, you runmapbut don't save or return its output. Theconsole.logworks 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
propvalue—this is more efficient and cleaner. - Returned the JSX: The
mapresult is now returned from the function, so your component can receive and render the<div>elements. - Handled Invalid Cases: If the input
propdoesn't match a valid index, we returnnullto 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

