所以,我的屏幕代码看起来像这样。我有一个 amount
的 useState,它在重新渲染时不断重置为初始值。我大约有三个 useEffects。其中一个在此示例代码中,我正在从数据库中获取金额,并使用 setAmount 进行设置。
const ConfirmPaymentDialog = props => {
const getInitialVal = () => {
console.log('Initial Amount: 0');
return conversions.numberToBigNumber(0);
};
const [amount, setAmount] = useState<BigNumber>(getInitialVal());
useEffect(() => {
getAmountToPay();
},[]);
const getAmountToPay = async () => {
const amount = await myDbModule.getAmount(customer.id);
console.log('DB Amount: ' + amount?.toString());
setAmount(amount || conversions.numberToBigNumber(0));
};
useEffect(() => {
...
}, [isInputTextFocused])
console.log('Rendering');
return (<View>...</View>);
}
当我打开这个屏幕时,控制台输出以下日志:
LOG Initial Amount: 0
LOG Rendering
LOG DB Amount: 500
LOG Initial Amount: 0
LOG Rendering
LOG Initial Amount: 0
LOG Rendering
LOG Initial Amount: 0
LOG Rendering
LOG Initial Amount: 0
LOG Rendering
LOG Initial Amount: 0
LOG Rendering
如何避免在重新渲染时,useState返回默认值?
useState(conversions.numberToBigNumber(0))
,行为也是相同的。 - Rishabh876useState(() => conversions.numberToBigNumber(0))
。 - Ori Drori