演示的网址。https:/4ikgc.csb.app。
为什么外层HTML总是 <h1>abc</h1>
顺便说一下,为什么控制台好像把所有的东西都记录了两次。
现在 console.log 的内容是。
render h1: {current: null} undefined
render h1: {current: null} undefined
second abc <h1>abc</h1>
forth abc <h1>abc</h1>
first abc <h1>abc</h1>
first abc <h1>abc</h1>
third hello1 <h1>abc</h1>
third hello1 <h1>abc</h1>
fifth hello2 <h1>abc</h1>
fifth hello2 <h1>abc</h1>
render h1: <h1>hello3</h1> <h1>abc</h1>
render h1: <h1>hello3</h1> <h1>abc</h1>
但我认为正确的内容是:
render h1: {current: null} undefined
second abc <h1>abc</h1>
forth abc <h1>abc</h1>
first abc <h1>abc</h1>
third hello1 <h1>abc</h1>
fifth hello2 <h1>abc</h1>
render h1: <h1>hello3</h1> <h1>hello3</h1>
希望有人能帮助我! 非常感谢!
import React from "react";
class Hello extends React.Component {
constructor(props) {
super(props);
this.h1 = React.createRef();
this.state = {
name: "abc"
};
}
componentDidMount() {
this.setState((state, props) => {
console.log("first", state.name, this.h1.outerHTML);
return {
name: "hello1"
};
});
console.log("second", this.state.name, this.h1.outerHTML);
this.setState((state, props) => {
console.log("third", state.name, this.h1.outerHTML);
return {
name: "hello2"
};
});
console.log("forth", this.state.name, this.h1.outerHTML);
this.setState((state, props) => {
console.log("fifth", state.name, this.h1.outerHTML);
return {
name: "hello3"
};
});
}
render() {
console.log("render h1:", this.h1, this.h1.outerHTML);
return <h1 ref={ref => (this.h1 = ref)}>{this.state.name}</h1>;
}
}
export default Hello;
你的Hello组件有一个 H1
以及你在哪里使用那个 Hello
组成部分也有另一个 H1
<div className="App">
<Hello />
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
你得到2的原因 console.logs
是如何反应生命周期的工作。您的第1 console.log
在 render
发生在组件最初被渲染的时候。当组件被渲染后,react会触发 componentDidUpdate
生命周期方法。
然后当你触发一个 this.setState
在该方法中,它触发了对 render
再来一次 这是你的第二个 console.log
. 也因为在你的特殊情况下,你设置的是... this.state
多次 componentDidUpdate
它会触发多个状态变化。
另外请注意,当在 development
模式,并使用反应严格 <React.StrictMode>
జజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ setState
被叫两次。这是故意的。在生产中不会发生。
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
REF: https:/github.comfacebookreactissues12856#issuecomment-390206425。
https:/reactjs.orgdocsstrict-mode.html#detecting-unexpected-side-effects。