为什么 outerHTML 总是<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;