reactjs - 钩子的值不更新
问题描述
我有以下内容:
const [quantityKm, setQuantityX] = useState({ x: 0 });
我有一个范围,当它更改时执行以下功能
const handleKmValue = (event) => {
const { x } = event;
setQuantityX({ x: x});
};
然后,如果我改变了<select>
这个函数,必须执行
const calculatePrice = () => {
console.log(quantityKm.x);
setValueMonth((parseFloat(quantityKm.x.toFixed(2)) * valueOfKm))
};
但是,我总是收到值为quantityKm.x
0
解决方案
从您的评论中,听起来您的代码结构如下:
const [quantityKm, setQuantityX] = useState({ x: 0 });
const handleKmValue = ...
const calculatePrice = ...
const handleChange = event => {
handleKmValue(event);
calculatePrice();
}
<Select onChange={handleChange} />
相反,使用:
const [quantityKm, setQuantityX] = useState({ x: 0 });
useEffect(() => {
// move the calculatePrice functionality into the effect
console.log(quantityKm.x);
setValueMonth((parseFloat(quantityKm.x.toFixed(2)) * valueOfKm))
}, [quantityKm.x]) // run effect if value's changed
<Select onChange={handleKmValue} />