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

时间:2020-03-28 16:39:50

标签: react-native react-native-android react-hooks

所以我在屏幕上的代码看起来像这样。我有一个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重置为默认值

1 个答案:

答案 0 :(得分:1)

它实际上并未重置为初始值。您只需继续调用函数即可生成初始值。与其调用它,不如将其作为回调(请参见lazy initial state)传递到useState()钩子,它将被调用一次:

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