gpt4 book ai didi

javascript - 消息在控制台中安慰两次 - ReactJS

转载 作者:行者123 更新时间:2023-12-01 00:04:35 25 4
gpt4 key购买 nike

下面是我非常简单的应用程序,它在 componentDidMount 生命周期中将计数从 10 增加到 11,但在控制台中 10 和 11 出现了两次。我很想知道为什么它会带来两次安慰。

代码-

import React from "react";
import "./styles.css";

export default class App extends React.Component {
state = {
count: 10
};
componentDidMount() {
this.setState(prevState => {
return {
count: prevState.count + 1
};
});
}
render() {
console.log(this.state.count);
return (
<div className="App">
<div
style={{
width: "100px",
height: "100px",
background: "#efdef3",
color: "black"
}}
>
Count is {this.state.count}
</div>
<h3>Hello Frwo</h3>
</div>
);
}
}

输出 -

10

10

11

11

CodeSandbox 链接 - https://codesandbox.io/s/reverent-elbakyan-yszki

让我知道我在这里做错了什么。

最佳答案

标准行为是在 componentDidMount 之前渲染一次(值为 10 ),在状态更新之后渲染一次(值为 11 )。

但在严格模式下,只有在开发模式下才会有额外的重新渲染:

It's an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for components with Hooks because those are more likely to accidentally have side effects in the wrong place.

https://github.com/facebook/react/issues/15074

关于javascript - 消息在控制台中安慰两次 - ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469506/

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