在 React JS 中渲染 n 级嵌套对象的最有效方法是什么?

我有一个来自 API 的数据,如下所示 -


{

  "expression": [

    "a",

    "b"

  ],

  "groups": [

    {

      "expression": [


      ],

      "groups": [

        {

          "expression": [

            "c",

            "d"

          ],

          groups: null

        }

      ]

    },

    {

      "expression": [

        "p",


      ],

      groups: null

    }

  ]

}

我必须呈现表达式和组(也包括表达式和多个组)。构建块是一个表达式。我们需要将嵌套表达式显示为组。


我尝试使用递归函数调用,但对于深度较大的对象,效率并不高。


这是类似于我的试验的东西-


let conditionStack = [];

  function parseInnerConditions(conditionObj) {

    if (conditionObj.expression) {

      conditionObj.expression.map((each, index) => {

        conditionStack = [

          ...conditionStack,

          <NewExpression key={index} conditionExpression={each} />, //renders an expression

        ];

      });

    }

    if (conditionObj.groups && conditionObj.groups.length) {

      return conditionObj.groups.map((child, index) => {

        conditionStack = [

          ...conditionStack,

          <ConditionGroup key={index}> // renders a block or group of expressions

            {parseInnerConditions(child)}

          </ConditionGroup>,

        ];

      });

    }

    return conditionStack;

  }


  return (

    <div>

    parseInnerConditions(conditionObject)

    </div>

  )

提前致谢。


胡说叔叔
浏览 170回答 2
2回答

梦里花落0921

您的map()回调没有return值,但在第二个if语句中,您将返回数组,因此[undefined, undefined, ...]当您递归到每个groups.要修复您的解决方案,请将您的.map()to更改为.forEach()并删除return之前的关键字conditionObj.groups.map(...)。不过,这里有一个更好的方法:function ConditionGroup ({ expression, groups }) {&nbsp; const conditionExpressions = useMemo(&nbsp; &nbsp; () => expression && expression.map(&nbsp; &nbsp; &nbsp; (value, index) => (&nbsp; &nbsp; &nbsp; &nbsp; <NewExpression key={index} conditionExpression={value} />&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; ),&nbsp; &nbsp; [expression]&nbsp; );&nbsp; const conditionGroups = useMemo(&nbsp; &nbsp; () => groups && groups.map(&nbsp; &nbsp; &nbsp; (value, index) => (&nbsp; &nbsp; &nbsp; &nbsp; <ConditionGroup key={index} {...value} />&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; ),&nbsp; &nbsp; [groups]&nbsp; );&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {conditionExpressions}&nbsp; &nbsp; &nbsp; {conditionGroups}&nbsp; &nbsp; </div>&nbsp; );}请注意, using indexas the key是一个反模式。理想情况下,如果提供了唯一 ID,您将希望使用唯一 ID。有关更多信息,请参阅ReactJS:在数组元素中给出键的最佳方法是什么。

HUWWW

ReactJS 是一个用于生成 UI的基于组件的库。因此,从组件的角度考虑,您的数据是一个组,而该组又将包含一个表达式和其他类似自身的组。分解这一点,我们可以形成三个组成部分:Expression&nbsp;用于简单地渲染组中的表达式。Group&nbsp;用于渲染组。Groups用于提取和渲染Group组件以供数据中的进一步组使用。这是一个示例代码:Index.js&nbsp;这是从 API 获取数据的文件。import React from "react";import Group from "./Group";const data = {&nbsp; expression: ["a", "b"],&nbsp; groups: [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; expression: [],&nbsp; &nbsp; &nbsp; groups: [{ expression: ["c", "d"], groups: null }]&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; expression: [],&nbsp; &nbsp; &nbsp; groups: [&nbsp; &nbsp; &nbsp; &nbsp; { expression: ["e", "f"], groups: null },&nbsp; &nbsp; &nbsp; &nbsp; { expression: ["g", "h"], groups: null }&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; expression: ["p"],&nbsp; &nbsp; &nbsp; groups: null&nbsp; &nbsp; }&nbsp; ]};const stage = 1;const Main = () => {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <Group data={data} stage={stage} />&nbsp; &nbsp; </div>&nbsp; );};export default Main;Group.js 用于渲染组。import React from "react";import Expression from "./Expressions";import Groups from "./Groups";const populateGroup = (data, stage) => {&nbsp; const HTML = [];&nbsp; for (const x in data) {&nbsp; &nbsp; if (x === "expression") {&nbsp; &nbsp; &nbsp; HTML.push(<Expression expression={data[x]} />);&nbsp; &nbsp; }&nbsp; &nbsp; if (x === "groups") {&nbsp; &nbsp; &nbsp; HTML.push(<Groups data={data[x]} stage={stage} />);&nbsp; &nbsp; }&nbsp; }&nbsp; return HTML;};const Group = ({ data, stage }) => {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <p>{`Group @ Stage ${stage}`}</p>&nbsp; &nbsp; &nbsp; <ol className="Group">{populateGroup(data, stage + 1).map(el => el)}</ol>&nbsp; &nbsp; </div>&nbsp; );};export default Group;Expression.js 用于简单地渲染组中的表达式。import React from "react";const Expression = ({ expression }) => {return (&nbsp; &nbsp; <div className="expression">&nbsp; &nbsp; &nbsp; {expression.map(term => (&nbsp; &nbsp; &nbsp; &nbsp; <h3 style={{ display: "inline" }}>{term}</h3>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </div>&nbsp; );};export default Expression;Groups.js用于提取然后渲染Group组件。import React from "react";import Group from "./Group";const Groups = ({ data, stage }) => {&nbsp; if (data === null) return <span></span>;&nbsp; return (&nbsp; &nbsp; <div className="GroupsSection">&nbsp; &nbsp; &nbsp; {data.map((section, i) => (&nbsp; &nbsp; &nbsp; &nbsp; <Group key={i} data={section} stage={stage} />&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </div>&nbsp; );};export default Groups;性能使用这种基于组件的方法,数据被分块,这应该可以提高性能以获得更好的结果,for...in并且map可以用for循环替换。&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript