求助:修复React Json LD动态面包屑组件三级及以上路径URL拼接错误
Got it, let's sort out this URL bug in your breadcrumb schema. The core problem here is that your current URL-building logic only looks at the immediately preceding segment instead of accumulating all previous segments for paths deeper than two levels.
Why the Current Code Breaks
This line is the root of the issue:
const url = index === 0 ? `${baseURL}/${segment}` : `${baseURL}/${segments[index - 1]}/${segment}`;
Take a 3-segment path like page/subpage/another-page as an example:
- When
index=0(first segment "page"), it works fine:baseURL/page - When
index=1(second segment "subpage"), it still works:baseURL/page/subpage - When
index=2(third segment "another-page"), it buildsbaseURL/subpage/another-page— it only uses the previous single segment ("subpage") instead of all prior segments ("page/subpage").
The Fix: Accumulate All Previous Segments
Instead of just grabbing the last segment, we need to take all segments from the start up to the current one, then join them into a full path. Replace that problematic line with this:
const fullPath = segments.slice(0, index + 1).join('/'); const url = `${baseURL}/${fullPath}`;
Here's what this does:
segments.slice(0, index + 1)grabs every segment from position 0 to the current index (inclusive). Forindex=2, this pulls["page", "subpage", "another-page"].join('/')turns that array into a single string:"page/subpage/another-page"- Prepending the base URL gives us the full, correct path.
Modified Full SCRIPT_BODY Function
Here's how your updated function will look:
const SCRIPT_BODY = dynamicSlug => { const slug = dynamicSlug.substring(1); const segments = slug.split("/"); const baseURL = `${process.env.CW_BASE_URL}`; return ` { "@context": "http://schema.org", "@type": "BreadcrumbList", "itemListElement": [ { "@type": "ListItem", "position": 1, "item": { "@type": "Thing", "@id": "${baseURL}", "name": "Home", "image": "" } }, ${segments.map((segment, index) => { // Fixed URL building logic const fullPath = segments.slice(0, index + 1).join('/'); const url = `${baseURL}/${fullPath}`; return ` { "@type": "ListItem", "position": ${index + 2}, "item": { "@type": "Thing", "@id": "${url}", "name": "${capitalizeEachWord(segment.toLowerCase().replace(/-/g, " "))}", "image": "" }} `; })} ] } `; };
Quick Validation
For a path like mysite.com/page/subpage/another-page:
- The third list item's
@idwill now correctly bemysite.com/page/subpage/another-pageinstead of the brokenmysite.com/subpage/another-page.
This approach works for any number of path segments (2, 3, 4, etc.) since it dynamically builds the full path from all prior segments.
内容的提问来源于stack exchange,提问作者Agustin G.

