嗨,我有以下代码:我的代码
在代码中,我从后端接收数据,在我的例子中,我硬编码了这个部分(参见下面的数据)。
const skills = [
{
id: 1,
name: "Html "
},
{ id: 2, name: "CSS" },
{ id: 3, name: "Scss" },
{ id: 4, name: "Bootstrap 4" },
{ id: 5, name: "JavaScript" },
{ id: 6, name: "Jquery" },
{ id: 7, name: "React JS" },
{ id: 8, name: "Angular " },
{ id: 9, name: "Vue.js " },
{ id: 10, name: "SQL" },
{ id: 11, name: "php" },
{ id: 12, name: "Laravel" }
];我正在数我的所有技能名称,炭长度,如果长度更长,那么allowCharCount,我隐藏了所有的休息技能,并在数量上显示了多少技能是隐藏的。那部分起作用了。
let lengthCount = 0;
let maxIndex = 0;
const allowCharCount = 20;
const skill = [];
export const Skill = ({ data }) => {
if (data === undefined) {
return null;
} else {
data.map((item) => {
if (lengthCount <= allowCharCount) {
maxIndex = item.id;
skill.push(item);
}
lengthCount += item.name.length;
});
const mySkills = skill.map((perSkill) => (
<span key={perSkill.id} className="skillItem">
{perSkill.name}
</span>
));
return (
<div className="skillWrapper">
<div>{mySkills}</div>
{lengthCount > allowCharCount ? (
<div className="skillNumber">+{data.length - maxIndex}</div>
) : null}
</div>
);
}
};但是当我的字符数小于allowCharCount时,它就不起作用了。
如果我只有前3项(Html、CSS、Scss),我会看到以下视图
Html CSS Scss Html CSS Scss +0。
请帮助我修复这种情况下的代码(如果chars计数小于allowCharCount),我只需要显示没有任何+0计数的正确项。
发布于 2021-03-04 13:31:00
您应该重新考虑编写组件和代码的一般方式。
.map方法返回内部回调返回的值数组。如果您不打算返回任何内容,请使用.forEach代替.length属性,而不是自己增加数组的大小,以避免bug。获得重复元素的原因是在组件更新之前没有清除数组,因此算法只是再次推送这些值。
工作代码示例:
export const Skill = ({ data }) => {
// here I invert condition to get the rest code out of brackets
if (!data) return null;
// all of the dynamic data should be inside the component
const failIndex = React.useMemo(() => {
let charCount = 0;
for (let i = 0; i < data.length; i++) {
charCount += data[i].name.length;
if (charCount > allowCharCount) return i;
}
return -1;
}, [data]);
// check if data has element that doesn't pass the condition
const dataBeforeFail = failIndex === -1 ? data : data.slice(0, failIndex + 1);
const hiddenSkillsCount = data.length - dataBeforeFail.length;
return (
<div className="skillWrapper">
<div>
{dataBeforeFail.map((perSkill) => (
<span key={perSkill.id} className="skillItem">
{perSkill.name}
</span>
))}
</div>
{hiddenSkillsCount > 0 && (
<div className="skillNumber">+{hiddenSkillsCount}</div>
)}
</div>
);
};https://stackoverflow.com/questions/66475300
复制相似问题