gpt4 book ai didi

reactjs - 为什么console.log 在react js 中记录两次?

转载 作者:行者123 更新时间:2023-12-04 11:51:10 30 4
gpt4 key购买 nike

我已经开始学习 React,但我无法理解为什么 console.log 会记录两次。下面是我的代码,当我在 chrome 中检查它时,它会显示“随机文本”这个词两次而不是一次。

import React, { Component } from "react";

class Counter extends Component {
state = {
count: 0

};



render() {
console.log('random-text');

return (
<div>
<span className={this.getBaadgeClasses()}>{this.formatCount()}</span>
<button
onClick={this.handleIncrement}
className="btn btn-success m-2"
>
Increment
</button>

{/* <ul>
{this.state.tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul> */}
</div>
);
}

getBaadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.count === 0 ? "warning" : "primary";
return classes;
}

formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}

handleIncrement = () => {
this.setState({count: this.state.count + 1})
}

}

export default Counter;

最佳答案

渲染函数是一个生命周期函数,在“渲染阶段”调用

enter image description here

react lifecycle methods diagram

请注意,这些函数是纯函数,可以由 React 暂停、中止或重新启动。这意味着 react 可以调用 render 几乎任意次数来协调 virtualDOM 与实际 DOM。

Detecting unexpected side effects

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.



如果您真的想要在组件更新使用其他生命周期函数之一时的一对一控制台日志,例如 componentDidUpdate做记录细节的副作用。
class Counter extends Component {
state = {
count: 0
};

componentDidUpdate() {
console.log("random-text");
}

render() {
return (
<div>
<span className={this.getBaadgeClasses()}>{this.formatCount()}</span>
<button onClick={this.handleIncrement} className="btn btn-success m-2">
Increment
</button>

{/* <ul>
{this.state.tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul> */}
</div>
);
}

getBaadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.count === 0 ? "warning" : "primary";
return classes;
}

formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}

handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
};
}

Edit use lifecycle function to log

关于reactjs - 为什么console.log 在react js 中记录两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62185425/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com