React Native 重新呈现时,useState始终重置为initialValue

iqjalb3h  于 2023-02-05  发布在  React
关注(0)|答案(1)|浏览(166)

我的屏幕代码看起来像这样。我有一个useState amount,它在重新呈现时会一直重置为initialValue。我有大约3个useEffects。其中一个在这里的示例代码中,我从db获取数量,并使用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在重新渲染时重置回默认值

xxe27gdn

xxe27gdn1#

它实际上并没有被重置为初始值,你只是不断地调用生成初始值的函数。
不要调用它,而是将它作为回调(参见lazy initialstate)传递给useState()钩子,它将被调用一次:

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

相关问题