【问题标题】:Conditionally mapping two different arrays into a React component depending on boolean value根据布尔值有条件地将两个不同的数组映射到一个 React 组件
【发布时间】:2022-01-11 14:28:31
【问题描述】:

我目前有一个名为 options 的数组,它被映射到一个 React 组件中,如下所示:

{options.map((option) => (
   <Component key={option.code}></Component>
))}

但是,我正在尝试扩展我的组件,以便如果布尔值:shouldCount 为真,则将 optionsWithCount 数组而不是 options 数组传递给组件。上面的组件有比显示更多的道具等,所以我想尽可能避免使用所有道具重复组件。

谁能提出一个可行的解决方法?

【问题讨论】:

  • 在渲染之前保存你想要的数组,然后使用相同的map函数呢?

标签: javascript reactjs


【解决方案1】:

使用 utils 函数 getOptions() 会起作用吗?它将shouldCount 标志作为输入并返回所需的数组。示例:

{ 
  getOptions(shouldCount).map((option) => (
    <Component key={option.code}></Component>
  ));
}

const getOptions = (shouldCount) => {
  return shouldCount ? optionsWithCount : options;
}

【讨论】:

    【解决方案2】:

    您可以有条件地更新选项变量,因此您不必再次重写相同的代码。

    使选项成为一种状态;

    const [options, setOptions] = useState([])
    

    并使用useEffect 更新它;

    useEffect(()=>{
        if(shouldCount) setOptions([1,2,3,4,5])
        else setOptions([5,6,7,8,9])
    }, [shouldCount])
    

    这样,当 shouldCount 改变时,它会触发 useEffect 并改变 optinos 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2022-08-18
      • 2021-02-22
      • 2021-09-17
      • 2021-07-04
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多