通过使用useRef获取上一次state值
function PrevState() {
const [currentCity, setCurrentCity] = React.useState({});
const prevCityRef = React.useRef();
React.useEffect(() => {
prevCityRef.current = currentCity;
}, [currentCity]);
const handleChange = (value: cityObject) => {
setCurrentCity(value)
}
return (
<>
<Select onChange={(value) => handleChange(value)}>
{ cityList.map(it => ( <Option value={it}>{it.name}</Option> )}
</Select>
<h1>Now: {currentCity.name}, before: {prevCityRef.current.name}</h1>
</>
)
}