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

React Native中按层级子类别展示JSON数组的实现及无显示问题排查

Fixing Nested Category Rendering in React Native

Hey there! Let's figure out why your component isn't showing anything and fix it to get that nested category list you want.

What's Wrong With Your Original Code?

Let's break down the key issues:

  • You're passing a JSON string instead of parsed JS data: The terms variable is a template literal string, not actual JavaScript objects/arrays. When you called recursive(terms), the function tried to access .children on a string—which doesn't exist, so nothing rendered.
  • Recursive logic doesn't match your data structure: Your top-level terms is an array, but your function expected a single object. Also, using level++ caused incorrect indentation (it modifies the level variable in-place for sibling items).
  • Duplicate entries in sample JSON: Your original "Accessories" child had a duplicate "Accessories" entry—we'll fix that to match your desired output.

Corrected Component Code

Here's the fixed version that will render your nested categories properly:

import React from 'react'
import { View, Text, StyleSheet } from 'react-native'

const Categories = () => {
  // Parse the JSON string into a usable JavaScript array
  const terms = JSON.parse(`
    [
      { "term_id": 15, "name": "Uncategorized", "children": [ ] },
      { "term_id": 21, "name": "Clothing", "children": [
        { "term_id": 24, "name": "Accessories", "children": [
          { "term_id": 27, "name": "Bike", "children": [ ] },
          { "term_id": 28, "name": "Engine", "children": [
            { "term_id": 29, "name": "Bench", "children": [ ] }
          ] },
          { "term_id": 30, "name": "Airplane", "children": [ ] }
        ] },
        { "term_id": 23, "name": "Hoodies", "children": [ ] },
        { "term_id": 22, "name": "Tshirts", "children": [ ] }
      ] },
      { "term_id": 26, "name": "Decor", "children": [ ] },
      { "term_id": 25, "name": "Music", "children": [ ] }
    ]
  `)

  // Recursive function to render nested categories
  const renderCategories = (categories, level = 0) => {
    // Map over each category in the input array
    return categories.map((category) => (
      <View key={category.term_id} style={styles.categoryContainer}>
        <Text style={styles.categoryText}>
          {/* Add dashes based on current level for indentation */}
          {level > 0 ? "-".repeat(level) : ""}{category.name}
        </Text>
        {/* Recursively render children if they exist */}
        {category.children.length > 0 && renderCategories(category.children, level + 1)}
      </View>
    ))
  }

  return (
    <View style={styles.container}>
      {renderCategories(terms)}
    </View>
  )
}

// Basic styling to improve readability
const styles = StyleSheet.create({
  container: {
    padding: 16,
  },
  categoryContainer: {
    marginVertical: 4,
  },
  categoryText: {
    fontSize: 16,
  },
})

export default Categories

Key Improvements Explained

  • JSON Parsing: JSON.parse() converts your string data into actual JavaScript objects that React can work with—this was the biggest fix.
  • Recursive Function Overhaul: renderCategories now takes an array, maps over each category, and recursively renders its children with level + 1 (avoids in-place variable modification that broke indentation).
  • Key Prop: Added key={category.term_id} to comply with React's list rendering requirements.
  • Matching Desired Output: Updated the sample data to include "Bike", "Engine -> Bench", and "Airplane" as you specified.
  • Basic Styling: Added padding and vertical spacing to make the nested structure easier to read.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:57:29