在下面的基于我需要在循环中显示一个标签的临时布尔值的代码中,如果将临时设置为真,我必须只显示一次标签,无论有多少真正的布尔值,文本都必须只显示一次.但是下面的代码显示了3次,因为3个临时布尔值被设置为真.有没有人能帮帮我怎么做?

import React from 'react';
const MyComponent = () => {
const data = [
    { id: 1, name: 'Item 1', temp : false },
    { id: 2, name: 'Item 2', temp : false },
    { id: 3, name: 'Item 3', temp : true },
    { id: 4, name: 'Item 4', temp : true },
    { id: 5, name: 'Item 5', temp : true },
    { id: 6, name: 'Item 6', temp : false },
    { id: 7, name: 'Item 7', temp : false },
    { id: 8, name: 'Item 8', temp : false },
];
return (
    <div>
    {
        data.map((item) => {
        return (
        <div key={item.id}>
        <span>{item.name}</span>
        { item.temp ?
        <span> temp label displayed </span>
        : null
    }
    </div>
    );
})}
</div>
);
};
export default MyComponent;

Output: enter image description here

注意:我不能对任何值进行硬编码.

推荐答案

您可以使用某种类型的flag来判断是否需要呈现临时标签.

我这样解决它,我添加了一个useRef作为旗帜,并使用这个引用来跟踪我们是否已经呈现了temp label.

import React, { useRef } from "react";

const MyComponent = () => {
  const data = [
    { id: 1, name: "Item 1", temp: false },
    { id: 2, name: "Item 2", temp: false },
    { id: 3, name: "Item 3", temp: true },
    { id: 4, name: "Item 4", temp: true },
    { id: 5, name: "Item 5", temp: true },
    { id: 6, name: "Item 6", temp: false },
    { id: 7, name: "Item 7", temp: false },
    { id: 8, name: "Item 8", temp: false },
  ];

  const flag = useRef(null);

  return (
    <div>
      {data.map((item, idx) => {
        // set flag if the item is a temp item and the flag has not been set yet
        if (item.temp && flag.current === null) flag.current = idx;

        return (
          <div key={item.id}>
            <span>{item.name}</span>
            {flag.current === idx ? <span> temp label displayed </span> : null}
          </div>
        );
      })}
    </div>
  );
};
export default MyComponent;

实时预览a codesandbox

Reactjs相关问答推荐

是否可能有不同的加载器用于路径有查询参数和没有查询参数,或者在React Router 6中添加它们时有条件地跳过一个加载器?

For循环中的元素在Reaction中丢失挂钩

Reactjs中的chartjs和reaction-chartjs-2的问题

将动态元素中的输入数据传输到Reaction

为什么我的react虚拟化列表不显示滚动条,除非我确保高度低于rowCount*rowHeight?

为什么查询错误在处理后仍出现在控制台中?RTK查询+ React

如何获取用户在 GooglePlacesAutocomplete 中输入的文本?

如何删除 bootstrap 手风琴上的边框

生产部署:控制台中 Firebase 无效 api 密钥错误

我可以同时使用 Gatsby 和 NEXT.JS 吗?

React - 将一个充满空值的无限大小的数组存储在 ref 中是否可以,或者我应该重置数组吗?

React - 使用 useEffect 还是直接在 onChange 方法中更改值对性能最好?

为什么我的 Next.js (React) 组件只有在页面中时才有效?

在 React JS 中编辑表格数据

docker:来 automorphic 护进程的错误响应:未指定命令.的原因是什么?

当从数组中删除数据时,UseEffect 不会重新渲染,仅在添加数据时才会重新渲染

如何在react 中更新子组件中的变量?

getAttribute 函数并不总是检索属性值

为什么 React 会多次调用我的应用程序的某些函数?

如何在 React 中制作动画?