javascript - 如何在反应中的每个映射项目后更改计数?
问题描述
我在使用 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
......等等。
如果我可以进一步或更好地解释任何事情,请告诉我,非常感谢您的宝贵时间。欢迎任何帮助。快乐编码!
解决方案
推荐阅读
- java - 如何在java中检查未初始化的数组引用?
- html - Requests Sessions.get 接收到一个稍微不同的 HTML
- python-3.x - 如何修复:MSYS2 MinGW 中的 PyInstaller '您的平台尚不受支持'
- javascript - 我如何让这段代码打印出这个输出。我不断为 .buyproduct 定义不确定
- angular - 如何获得有关组件服务更改的通知?
- python - Slicing Multindex Time (first level) TypeError: '<' not supported between 'int' and 'slice'
- python - 在透明图像上使用自定义字体编写抗锯齿文本
- r - 如果 NA 出现在向量中,则使所有后续元素 NA
- terraform - 适用于 aws 的 Terraform 失败
- heroku - 获取 -bash: /usr/local/Bluemix/bx/bash_autocomplete: No such file or directory 错误