0

我在使用 React 正确实现这一点时遇到了麻烦,我会尽力解释这一点。

在这里,我有一个静态数字数组,其中包含 3 个不同的数字,我需要将它们应用于我的映射组件(OtherComponent)。这段代码直接在下面有效,但我认为我在 React 中使用了 count( heightCount ) 和我的静态数组( lineSegmentHeights ) 错误。

import React, { Fragment } from "react";
import { OtherCompnonent } from "./OtherComponent";

export const FuncComponent: React.FC<IProps> = (props) => {
  const lineSegmentHeights: number[] = [139, 88, 38];
  let heightCount: number = 0;

  return (
    <Fragment>
      {props.data.map((item, index) => {
        if (heightCount >= 3) {
          heightCount = 0;
        }
        heightCount++;

        return (
          <OtherComponent
            key={`${index - test}`}
            compData={item}
            lineSegmentHeight={
              lineSegmentHeight[minorMilestonesHeightCount - 1]
            }
          />
        );
      })}
    </Fragment>
  );
};

然后我试着用这个来监控计数useState

import React, { Fragment, useState } from "react";
import { OtherCompnonent } from "./OtherComponent";

export const FuncComponent: React.FC<IProps> = (props) => {
  const lineSegmentHeights: number[] = [139, 88, 38];
  const [heightCount, setHeightCount] = useState <number> 0;

  return (
    <Fragment>
      {props.data.map((item, index) => {
        if (heightCount >= 3) {
          heightCount(0);
        }
        setHeightCount(heightCount + 1);

        return (
          <OtherComponent
            key={`${index - test}`}
            compData={item}
            lineSegmentHeight={lineSegmentHeight[heightCount - 1]}
          />
        );
      })}
    </Fragment>
  );
};

这会导致很多生命周期渲染错误。

我的主要问题是我应该如何正确存储这个永远不会改变的静态值数组?另外我如何正确监控计数与反应,以便第一个映射的组件得到 a lineSegmentHeight === 139,下一个得到lineSegmentHeight === 88,下一个得到38,下一个得到139,下一个得到88......等等。

如果我可以进一步或更好地解释任何事情,请告诉我,非常感谢您的宝贵时间。欢迎任何帮助。快乐编码!

4

0 回答 0