我有以下内容:
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
答案 0 :(得分:1)
从您的评论看来,您的代码结构如下:
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} />