每当我使用useState设置一个变量时,其值不会立即反映出来。这里有一个useEffect调用computePriceSummary();
浏览器中显示的值为:
Stackoverflow中的解决方案建议使用useEffect来跟踪变量,因此我这样做了:
结果仍然是一样的。
useEffect(() => {
computePriceSummary();
}, []);
computePriceSummary 调用三个函数,如下所示:
const computePriceSummary = () => {
computeSubtotal();
computeTaxes();
computeTotal();
};
这些函数使用useState来设置变量:
const computeTaxes = () => {
let taxes = 0.05 * subtotal;
setTaxes(taxes);
};
const computeTotal = () => {
setTotal(taxes + subtotal);
};
const computeSubtotal = () => {
let subtotal = cart.products.reduce((acc, item) => {
return (acc += item.product.price * item.quantity);
}, 0);
setSubtotal(subtotal);
};
浏览器中显示的值为:
Subtotal: $1200
Taxes: $0
Total: $0
Stackoverflow中的解决方案建议使用useEffect来跟踪变量,因此我这样做了:
useEffect(() => {
console.log("Use effect to immediately set variables");
}, [subtotal, taxes, total]);
结果仍然是一样的。