在 React 组件中使用 ++ 运算符

Using ++ operator in react component

import React, { useState } from "react";
// import styles sheet:
import "./css/CommentBlock.css";

// import profile avatars:
import gamer from "./icons/gamer.png";
import man1 from "./icons/man (1).png";
import man from "./icons/man.png";
import user from "./icons/user.png";
import woman1 from "./icons/woman (1).png";
import woman from "./icons/woman.png";

let icons = [gamer, man1, man, user, woman1, woman];
let index = 0;

function CommentBlock(props) {
  // JS object destructuring:
  let { name, comment } = props;
  index ++;
  console.log(index);

  return (
    <li className="comment-block">
      <div className="avatar">
        <img src={icons[index % icons.length]} alt={name} />
      </div>
      <div className="comment-info">
        <h4 className="user-name">{name}</h4>
        <p className="comment-context">{comment}</p>
      </div>
    </li>
  );
}

export default CommentBlock;

索引值:1 3 5 7 9 11 ...

我对 React 组件中的 ++ 运算符感到很困惑。 我有 7 个评论块,但是当我在我的组件中使用索引 ++ 时。我希望该指数只增加一次。但指数值增加了两倍。

我想知道如何解决这个问题?

你遇到的问题是关于react render(react的生命周期), 事实上,在开发模式下,react 使用严格模式,这会导致组件的双重渲染,此外,您正在使用变量来保存数据,组件的任何渲染都会导致索引增加,我认为对于您的情况显示使用反应的状态。

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

Class component constructor, render, and shouldComponentUpdate methods Class component static getDerivedStateFromProps method Function component bodies State updater functions (the first argument to setState) Functions passed to useState, useMemo, or useReducer Note:

This only applies to development mode. Lifecycles will not be double-invoked in production mode.

https://reactjs.org/docs/strict-mode.html#gatsby-focus-wrapper

取自react官方文档 您可以阅读有关严格模式的内容以及有关 React 的状态和生命周期的更多解释。