import { Button } from 'antd';
import React, { useState } from 'react'
export default function Index() {
const [width, setWidth] = useState(1);
const [height, setHeight] = useState(1);
const getArea = () => {
return width * height;
}
return (
<div>
<span>{width}</span>
<br />
<span>{height}</span>
<Button type="primary" onClick={() => {
setWidth(width + 1);
setHeight(height + 1);
const area = getArea();
console.log('areat=', area); // 一直是上一个宽高的乘积
}}>add</Button>
</div>
)
}
问题:
- 为什么一直取到的是上一个值
- 怎么取到最新的state值
你要理解react的更新机制,你是直接在onClick里面同时引入了,setWidth, setHeight, getArea()方法,此时getArea 里面的引用是之前的width和height,并不是你 +1 后的width, height.
所以总是拿到上一次的值,要实施获取有两种方法。