如何在数组中添加这些元素以自定义reactjs中的代码

问题描述

我用很多if逻辑编写了代码。我正在尝试改善我的代码。谁能建议我一些更好的选择。我正在尝试根据条件打印数据: functionOne和secondFunction是将在多个位置返回组件的方法。 我的代码要点是:如果myFirstDataArray的长度大于3,则打印第二函数值,否则,请再次检查myFirstDataArray的长度,依此类推。

const functionOne = (data) => {
    return (
      <SummaryOfValues
        data={data}
      ></SummaryOfValues>
    );
  };

  const secondFunction = (data) => {
    return (
      <listofValues
        data={data.info}
      ></listofValues>
    );
  };

{
  myFirstDataArray && myFirstDataArray.length >= 3 ? (
    <>
      <>
        {resultedDataArray
          .slice(0,3)
          .map((data: any) => ({ secondFunction(data); }))}
      </>
    </>
  ) : (
    <>
      <>
        {resultedDataArray
          .slice(0,resultedDataArray.length)
          .map((data: any) => ({ secondFunction(data); }))}
      </>

      {myFirstDataArray && myFirstDataArray.length === 1 ? (
        <>
          {resultedDataArray
            .slice(myFirstDataArray.length)
            .map((data: any) => ({ functionOne(data); }))}
        </>
      ) : null}
      {myFirstDataArray && myFirstDataArray.length === 2 ? (
        <>
          {resultedDataArray
            .slice(myFirstDataArray.length,myFirstDataArray.length + 1)
            .map((data: any) => ({ functionOne(data); }))}
        </>
      ) : null}
    </>
  );
}

解决方法

您如何看待该解决方案?

const functionOne = (data) => {
    return (
        <SummaryOfValues
            data={data}
        ></SummaryOfValues>
    );
};

const secondFunction = (data) => {
    return (
        <ListOfValues
            data={data.info}
        ></ListOfValues>
    );
};

{
    myFirstDataArray && myFirstDataArray.length > 0 (
        <>
            <>
                {resultedDataArray
                    .slice(0,3)
                    .map((data: any) => ({ secondFunction(data); }))}
            </>
            {myFirstDataArray.length < 3 ? (
                <>
                    {resultedDataArray
                        .slice(myFirstDataArray.length - 1)
                        .map((data: any) => ({ functionOne(data); }))}
                </>
            ) : null}
            </>
        );
}