【问题标题】:map function reducing index not working (with React)映射函数减少索引不起作用(使用 React)
【发布时间】:2021-06-03 22:41:47
【问题描述】:

我正在尝试为从字符数组映射的每个 div 分配一个 className 有效名称(句点除外)。我在 map 函数中使用了 if 语句来返回所需的反应对象,它应该“忽略”句点并返回一个连续编号的 className,但它确实忽略了句点,但对 className 进行了错误编号。

Letters.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;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:
     else if (i === 5) { // && character === ".", or else we wouldn't get here
    

    如果character === ".",您将只能到达else,并且由于i === 4 如果这是真的,那么其他情况可能就不存在了。您可能想颠倒所有这些检查的顺序,if (character === ".") {} else if (i === 5) {} else { /* !== "." */ }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-16
      • 2018-08-14
      • 2021-03-13
      • 2011-12-23
      • 2016-01-22
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多