【问题标题】:How to define an array with conditional elements in react如何在反应中定义具有条件元素的数组
【发布时间】:2021-07-06 12:13:55
【问题描述】:

我有一个像这样的 tableFilterFields 数组:

 const tableFilterFields = [
    {
      label: "اfrom",
      name: "StartDate",
      type: FilterControls.DatePicker,
      defaultValue: new Date(new Date().setDate(new Date().getDate() - 3100)),
    }
    props.id === undefined
      ? {
          label: "عنوان شخص",
          name: "IdentityTitle",
          type: FilterControls.Input,
        },
        {
          label: "کد بورسی",
          name: "AccountCode",
          type: FilterControls.Input,
        },
         {
          label: "نماد ",
          name: "InstrumentPersianCode",
          type: FilterControls.Input,
        },
        {
      label: "نوع معامله ",
      name: "TradeSideTitle",
      type: FilterControls.Input,
        }
        
      : 


  {
            label: "نماد ",
            name: "InstrumentPersianCode",
            type: FilterControls.Input,
          },
          {
        label: "نوع معامله ",
        name: "TradeSideTitle",
        type: FilterControls.Input,
          },
      ];

我想应用一个条件,即 If prop is not undefined ....我应该怎么做?

【问题讨论】:

  • 当我以这种方式应用条件时,会出现语法错误

标签: javascript arrays reactjs react-hooks


【解决方案1】:

最好在数组定义之外做条件操作。您可以通过有条件地执行 push 操作

来实现此目的
if(props.id === undefined){
  tableFilterFields.push({
          label: "عنوان شخص",
          name: "IdentityTitle",
          type: FilterControls.Input,
        },
        {
          label: "کد بورسی",
          name: "AccountCode",
          type: FilterControls.Input,
        },
         {
          label: "نماد ",
          name: "InstrumentPersianCode",
          type: FilterControls.Input,
        },
        {
      label: "نوع معامله ",
      name: "TradeSideTitle",
      type: FilterControls.Input,
        })
} else {
     tableFilterFileds.push(  {
            label: "نماد ",
            name: "InstrumentPersianCode",
            type: FilterControls.Input,
          },
          {
        label: "نوع معامله ",
        name: "TradeSideTitle",
        type: FilterControls.Input,
          })
}

【讨论】:

    【解决方案2】:
    import React from "react";
    
    const index = ({ array }) => {
      if (array === undefined) return <>Array not found</>;
    
      return (
        <div>
          {array.map((x) => (
            <RenderArray key={x.id} {...x} />
          ))}
        </div>
      );
    };
    
    export default index;
    
    

    你可以为条件排序做这样的事情

    【讨论】:

      【解决方案3】:

      先插入常用元素,再有条件插入push其余部分:

      const arr = ["common"];
      const condition = undefined === void 0;
      arr.push.apply(arr, condition ? ["variant1", 2, 3] : ["variant2", 4, 5]);
      
      console.log(arr);

      【讨论】:

        猜你喜欢
        • 2017-12-08
        • 2019-11-27
        • 2020-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 2017-10-11
        • 1970-01-01
        相关资源
        最近更新 更多