gpt4 book ai didi

react-native - useState 在重新渲染时不断重置为 initialValue

转载 作者:行者123 更新时间:2023-12-04 15:32:30 26 4
gpt4 key购买 nike

所以我的屏幕代码看起来像这样。我有一个 useState amount,它在重新呈现时不断重置为 initialValue。我有大约 3 个 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 在重新渲染时重置回默认值

最佳答案

它实际上并没有重置为初始值。您只需继续调用生成初始值的函数即可。不要调用它,而是将它作为回调(参见 lazy initial state )传递给 useState() Hook ,它将被调用一次:

const [amount, setAmount] = useState<BigNumber>(getInitialVal); // getInitialVal instead of getInitialVal()

关于react-native - useState 在重新渲染时不断重置为 initialValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60903691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com