React ordinary class component
import React, {
Component} from 'react'
export default class App extends Component {
state = {
count: 0
}
render() {
const {
count } = this.state
return (
<div>
<button
type="button"
onClick={
() => {
this.setState({
count: count + 1 }) }}>
Click:{
count}
</button>
</div>
)
}
}
Functional components using react Hooks
import React, {
useState } from 'react'
function App() {
const [count, setCount] = useState(0)
//useState(),返回值是一个只有两个成员的数组,第一个是count本身,第二个是设置count的方法
return (
<div>
<button
type="button"
onClick={
() => setCount(count + 1)}>
Click:{
count}
</button>
</div>
);
}
export default App
If you need to use the count data directly after setCount, the old count data is still used. If you want to use the latest count data, you must cooperate with the useEffect hook. Just pass count in the second parameter of useEffect. The set callback is implemented in disguise. Effect
useEffect(() => {
console.log(count)}, [count])
[count] is used as the second parameter. When the component is re-rendered, React will compare the [count] of the previous rendering with the [count] of the next rendering. If there is a change, the effect will be executed, otherwise the effect will be skipped.