react中函数里一直取的是state的上一个值

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>
  )
}

问题:

  1. 为什么一直取到的是上一个值
  2. 怎么取到最新的state值
阅读 4.4k
1 个回答

你要理解react的更新机制,你是直接在onClick里面同时引入了,setWidth, setHeight, getArea()方法,此时getArea 里面的引用是之前的width和height,并不是你 +1 后的width, height.
所以总是拿到上一次的值,要实施获取有两种方法。


// 第一种 利用useEffect 动态计算 直接取area 就行了  只要width height 变化 就会重新计算

const [area, setArea] = useState(width * height)
useEffect(() => {
  setArea(width * height)
}, [width, height])

console.log(area);
// 第二种 不用声明getArea函数 因为你能拿到当前的值直接计算就行 
 <Button type="primary" onClick={() => {
        setWidth(width + 1);
        setHeight(height + 1);
        const area = (width + 1) * (height + 1);
        console.log('area=', area); 
      }}>add</Button>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题