【问题标题】:How to count for each mapped element?如何计算每个映射元素?
【发布时间】:2023-01-19 23:19:31
【问题描述】:

已解决 - 不知道 useRef 挂钩帮助我跟踪每个单独的映射项目。

我在卡片元素中映射了一组结果。我想为每个元素保留一个点击次数,但是使用全局 JS 变量,如果我在每个会话的多个可点击元素上调用该变量,它会计算所有元素的点击次数。我曾尝试做 id.index,添加 (id) + index 等,但被难住了。如何正确使用唯一 ID 来跟踪每张卡的索引?谢谢

function onClick(id) {
    let index = 0;
    index++;
    if (index >= 1) {
      dosomething
    } else if (index === 0) {
      dosomethingelse
    }
  }

【问题讨论】:

  • 由于您的项目在 React 中,您可能想检查状态是如何工作的,它们在组件中是全局的
  • 请包含更多代码
  • @PratikWadekar 我只需要找到一种方法将作为参数传递的 id 与我定义的索引结合起来,以便为每个映射项目创建唯一索引。
  • @MartijnVissers 是的,我考虑过使用状态来管理它,但这是一回事。我不确定如何为每个映射元素创建一个唯一实例。

标签: javascript reactjs


【解决方案1】:

目前还不清楚你想要计算什么以及如何计算和 onclick 事件。

假设您需要跟踪每个元素/id 的点击次数:
您可以使用 useRef 挂钩并将其保留为全局对象以跟踪每个 ID 的点击次数。

const clicksPerId = useRef({});

function onClick(id) {
   if (!clicksPerId.current[id]) {
       clicksPerId.current[id] = 0;
   }
   clicksPerId.current[id]++;

   // whatever you want to do with the clicks count
}

【讨论】:

  • 很抱歉在我原来的问题中不清楚。这就像一个魅力,非常感谢你。
【解决方案2】:

老实说,我对你的问题有点困惑,但是对于在 javascript / React 中使用数组,你可能会发现其中一些有用

  1. 获取数组长度

    const MyComponent = () => {
    
      const [myArray, setMyArray] = useState([1, 2]);
      
      // find the length of the array
      const getArrayLength = () => {
        return myArray.length;
      }
    
      return (
        <p>hello there</p>
      )
    }
    1. 对映射组件的索引做一些事情:

    const MyComponent = () => {
    
      const [myArray, setMyArray] = useState([1, 2]);
      
      const handleClick = (index) => {
        // do somthing with the index of the el
      };
    
      return (
        <>
          { myArray.map((el, index) => {
              return (
                <p
                  key={index}
                  onClick={() => handleClick(index)}
                 >
                  el number { el }
                </p>
              )
            }) 
          }
        </>
      )
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2021-11-11
    • 2012-11-18
    • 2017-02-22
    • 1970-01-01
    相关资源
    最近更新 更多