import React from "react";
export default class DefComponent extends React.Component{
constructor(props) {
super(props);
this.state = {
num: 1
}
this.onClick = this.onClick.bind(this);
}
componentWillMount() {
}
onClick() {
this.setState({
num: 2
})
setTimeout(() => {
this.setState({
num: 4
})
}, 2000)
}
render() {
const { num } = this.state;
console.log(num);
return (
<div onClick={this.onClick}>{num}</div>
)
}
}
控制台打印
2
2
4
4
会出现打印两次的情况
原因:
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import "./style.css";
import App from './App';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
// <StrictMode>
<App />
// </StrictMode>
);
index.js根元素上使用了严格模式,去掉即可