作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面是我非常简单的应用程序,它在 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.
关于javascript - 消息在控制台中安慰两次 - ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469506/
我是一名优秀的程序员,十分优秀!