首先,我在控制台中为每个生命周期挂钩添加了日志
class CircleA extends Component {
constructor(props) {
super(props);
this.state = {
name: "Circle",
};
console.log("Circle-A constructor");
}
static getDerivedStateFromProps(props, state) {
console.log("Circle-A getDeriveStateFromProps Method");
return null;
}
componentDidMount() {
console.log("Circle-A componentDidMount Method");
}
render() {
console.log("Circle-A render method");
return <div>Circle-A</div>;
}
}
然后,在控制台上,直到componentDidMount
的每个方法都被调用了两次,而没有更新状态。
这些是控制台消息
答案 0 :(得分:1)
这可能是由于React.StrictMode
引起的。 React可以多次调用渲染阶段方法来检测副作用。您可能要检查使用ReactDOM.render
的index.js文件或主文件,以检查是否有一个名为React.StrictMode
的包装器。
以下是同一文档:https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
希望这会有所帮助!