简体   繁体   English

map function 减少索引不起作用(使用 React)

[英]map function reducing index not working (with React)

I am trying to assign a className for each div mapped from an array of characters valid names except for a period.我正在尝试为从字符数组映射的每个 div 分配一个 className 有效名称(句点除外)。 I used if-statements inside the map function to return the desired react object and it is supposed to "ignore" the period and return a continuous numbered className but instead it does ignore the period but numbers the className incorrectly.我在 map function 中使用了 if 语句来返回所需的反应 object 并且它应该“忽略”句点并返回一个连续编号的类名 className 但它确实忽略了数字。

Letters.js字母.js

import { Fragment } from "react";

const Letters = () => {
  const characters = "STRI.G".split("");

  const stringBuilder = characters.map((character, i) => {
    if (character !== ".") {
      return <div className={`type${i + 1}`}>{character}</div>; // Works
    } else if (i === 5) {
      // If index value reached the value after '.'
      return <div className={`type${i - 1}`}>{character}</div>; // Does not work, className here remains "type6" instead of "type5"
    } else {
      return <div>{character}</div>; // For when character === '.'
    }
  });

  return <Fragment>{stringBuilder}</Fragment>;
};

export default Letters;
 else if (i === 5) { // && character === ".", or else we wouldn't get here

you'll only ever get to that else if character === "."如果 character === "." 你只会得到那个else if character === "." , and since i === 4 when that is true, this else might as well not be there. ,并且由于i === 4当这是真的时,否则这也可能不存在。 You probably want to reverse the order of all of these checks, if (character === ".") {} else if (i === 5) {} else { /*.== "." */ }您可能想要颠倒所有这些检查的顺序, if (character === ".") {} else if (i === 5) {} else { /*.== "." */ } if (character === ".") {} else if (i === 5) {} else { /*.== "." */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM