问题
在setState方法执行之后,再执行自定义的方法,这个自定义方法里面获取不到最新的state状态
import React, {useState} from "react";
import { Button } from "antd"
const Demo = () => {
const [num, changeNum] = useState(1)
const [str, changeStr] = useState("现在数字是1")
const getNum = () => {
const newStr = "现在数字是" + num
console.log(newStr)
changeStr(newStr)
}
const setNum = () => {
// 使用 async await 自执行函数 setTimeout 都没用
changeNum(num + 1)
// 执行之后 getNum里拿不到最新的state
getNum()
}
return (
<div>
<Button onClick={setNum}>点我+1</Button>
<div>{num}</div>
<div>{str}</div>
</div>
)
}
export default Demo
解决方法
第一种
通过useEffect方法监听num 再去触发getNum函数
useEffect(() => {
getNum()
}, [num])
const getNum = () => {
const newStr = "现在数字是" + num
changeStr(newStr)
}
const setNum = () => {
changeNum(num + 1)
}
第二种
const numRef = useRef(1)
const [num, changeNum] = useState(numRef.current)
const [str, changeStr] = useState("现在数字是1")
const getNum = () => {
const newStr = "现在数字是" + numRef.current
changeStr(newStr)
}
const setNum = () => {
numRef.current = num + 1
changeNum(numRef.current)
getNum()
}
完整第一种代码
import React, {useState, useEffect} from "react";
import { Button } from "antd"
const Demo = () => {
const [num, changeNum] = useState(1)
const [str, changeStr] = useState("现在数字是1")
useEffect(() => {
getNum()
}, [num])
const getNum = () => {
const newStr = "现在数字是" + num
changeStr(newStr)
}
const setNum = () => {
changeNum(num + 1)
}
return (
<div>
<Button onClick={setNum}>点我+1</Button>
<div>{num}</div>
<div>{str}</div>
</div>
)
}
export default Demo
完整第二种代码
import React, {useState, useEffect, useRef} from "react";
import { Button } from "antd"
const Demo = () => {
const numRef = useRef(1)
const [num, changeNum] = useState(numRef.current)
const [str, changeStr] = useState("现在数字是1")
const getNum = () => {
const newStr = "现在数字是" + numRef.current
changeStr(newStr)
}
const setNum = () => {
numRef.current = num + 1
changeNum(numRef.current)
getNum()
}
return (
<div>
<Button onClick={setNum}>点我+1</Button>
<div>{num}</div>
<div>{str}</div>
</div>
)
}
export default Demo