[英]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 className="comment-info"> <h4 className="user-name">{name}<\/h4> <p className="comment-context">{comment}
<\/li> ); } export default CommentBlock;<\/code><\/pre> index value: 1 3 5 7 9 11 ...<\/strong>
指数值:1 3 5 7 9 11 ...<\/strong>
I'm really confused about ++ operator in react component.我对反应组件中的 ++ 运算符感到非常困惑。 I have 7 comment block but when I use index ++ in my component.
我有 7 个注释块,但是当我在组件中使用索引 ++ 时。 I expect that index increases just one time.
我预计该指数只会增加一次。 but index value increased for two times.
但指数值增长了两倍。
I want to know how solve this problem ?<\/strong>我想知道如何解决这个问题?<\/strong>
"
The problem you are facing is about react render (the lifecycle of react), and the fact that in development mode, react uses Strict Mode, which causes a double render of your component, moreover, you are using a variable to hold your data, any render of your component cause the index increase, I think for your case you show use the react's state.您面临的问题是关于反应渲染(反应的生命周期),事实上,在开发模式下,反应使用严格模式,这会导致您的组件双重渲染,此外,您正在使用一个变量来保存您的数据,您的组件的任何渲染都会导致索引增加,我认为对于您的情况,您显示使用反应的状态。
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:
类组件构造函数、render 和 shouldComponentUpdate 方法 类组件静态 getDerivedStateFromProps 方法 函数组件主体 状态更新器函数(setState 的第一个参数) 传递给 useState、useMemo 或 useReducer 的函数 注意:
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 https://reactjs.org/docs/strict-mode.html#gatsby-focus-wrapper
Taken from react official docs you can read about the strict mode and more explained about the state and the lifecycle of react.取自 react 官方文档,您可以阅读有关严格模式的信息以及有关 react 的状态和生命周期的更多说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.