链接React.useEffect依赖关系会导致缓慢的重新渲染

时间:2020-07-27 09:46:41

标签: reactjs react-native react-hooks use-effect use-state

我正在创建一个用于“购买”加密货币的屏幕,并且已经按照附件中的图像组织了组件。当我更改EUR输入金额时,我期望计算会非常快,因为不涉及任何API调用(仅涉及基本的数学运算)。由于我将useEffect状态和更新功能从BuyScreen传递到了props到CurrencyWidget和FeeSummary作为道具,因此我需要(据我所知)使用useEffect和一个值依赖项,以确保我拥有上次更新的值。

问题在于UI更新的速度(see GIF)有多慢,因为我正在更改多个useEffect挂钩以确保我拥有所有更新的值。我的代码中有什么可以改进的地方来解决此问题?

components hierarchy

BuyScreen.js

const calculateTotalBuyTransactionAmount = (
  buySourceAmount,
  cryptoBuyPrice
) => {
  return (buySourceAmount / cryptoBuyPrice).toFixed(8);
};

const calculateSubtotal = (amount, fees) => {
  return (amount - fees).toFixed(2);
};

const BuyScreen = (props) => {
  const [buySourceAmount, setBuySourceAmount] = useState(0.0);
  const [buyDestinationAmount, setBuyDestinationAmount] = useState(0.0);
  const [feeAmount, setFeeAmount] = useState(0.0);
  const [feeSubTotalAmount, setFeeSubTotalAmount] = useState(0.0);
  const [cryptoBuyPrice, setCryptoBuyPrice] = useState(
    pricesMock[0].values.prices.EUR.buy
  );

  useEffect(() => {
    setFeeAmount((buySourceAmount * 0.05).toFixed(2));
  }, [buySourceAmount]);

  useEffect(() => {
    setFeeSubTotalAmount(calculateSubtotal(buySourceAmount, feeAmount));
  }, [feeAmount]);

  useEffect(() => {
    setBuyDestinationAmount(
      calculateTotalBuyTransactionAmount(feeSubTotalAmount, cryptoBuyPrice)
    );
  }, [feeSubTotalAmount]);

  console.log("Rendering BuyScreen");

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <Container>
        <Content padder>
          <View>
            <CurrencyWidget
              currencyName={balancesMock.values.currencyBalances[0].name}
              currencyCode={balancesMock.values.currencyBalances[0].code}
              balance={balancesMock.values.currencyBalances[0].total}
              inputAmount={buySourceAmount}
              setInputAmount={(amount) => {
                setBuySourceAmount(amount);
              }}
              autofocus
            />
            <FeesSummary
              feeAmount={feeAmount}
              feeSubTotalAmount={feeSubTotalAmount}
            />
            <RealTimeCryptoPriceWidget
              currencyCode={balancesMock.values.cryptoBalances[0].code}
              cryptoBuyPrice={cryptoBuyPrice}
            />
            <CurrencyWidget
              currencyName={balancesMock.values.cryptoBalances[0].name}
              currencyCode={balancesMock.values.cryptoBalances[0].code}
              balance={balancesMock.values.cryptoBalances[0].total}
              inputAmount={buyDestinationAmount}
              destinationCurrency
            />
          </View>
          <View>
            <LoadingSpinner area="buy-button">
              <Button
                block
                primary-light
                style={{
                  marginBottom: 16,
                }}
              >
                <Text>Buy {balancesMock.values.cryptoBalances[0].name}</Text>
              </Button>
            </LoadingSpinner>
          </View>
        </Content>
      </Container>
    </SafeAreaView>
  );
};

CurrencyWidget.js

const CurrencyWidget = (props) => {
  console.log("Rendering CurrencyWidget");
  return (
    <Grid>
      <Col>
        <Text notification-light>
          {props.currencyName} ({props.currencyCode})
        </Text>
        <Text label-light style={styles.balanceAmount}>
          Balance: {props.currencyCode} {props.balance}
        </Text>
      </Col>
      <Col style={{ alignItems: "flex-end", justifyContent: "flex-start" }}>
        <Item regular>
          <Input
            transactionAmount
            keyboardType="numeric"
            placeholder="0"
            editable={!props.destinationCurrency}
            autoFocus={props.autofocus}
            value={String(props.inputAmount)}
            onChangeText={(amount) => {
              console.log("amount: ", amount);
              amount === ""
                ? props.setInputAmount("0")
                : props.setInputAmount(amount);
            }}
          />
        </Item>
      </Col>
    </Grid>
  );
};

FeeSummary.js

const FeesSummary = props => {
  const sellPageFees = () => {
    return (
      <Grid style={styles.verticalPadding}>
        <Row>
          <Col style={styles.verticalCenter}>
            <Text label-light>Subtotal</Text>
          </Col>
          <Col style={[styles.verticalCenter, { alignItems: "flex-end" }]}>
            <Text notification-light-regular>
              EUR {props.feeSubTotalAmount}
            </Text>
          </Col>
        </Row>
        <Row>
          <Col style={styles.verticalCenter}>
            <Text label-light>Fees</Text>
          </Col>
          <Col style={[styles.verticalCenter, { alignItems: "flex-end" }]}>
            <Text notification-light-regular>EUR {props.feeAmount}</Text>
          </Col>
        </Row>
      </Grid>
    );
  };

  const buyPageFees = () => {
    return (
      <Grid style={styles.verticalPadding}>
        <Row>
          <Col style={styles.verticalCenter}>
            <Text label-light>Fees</Text>
          </Col>
          <Col style={[styles.verticalCenter, { alignItems: "flex-end" }]}>
            <Text notification-light-regular>EUR {props.feeAmount}</Text>
          </Col>
        </Row>
        <Row>
          <Col style={styles.verticalCenter}>
            <Text label-light>Subtotal</Text>
          </Col>
          <Col style={[styles.verticalCenter, { alignItems: "flex-end" }]}>
            <Text notification-light-regular>
              EUR {props.feeSubTotalAmount}
            </Text>
          </Col>
        </Row>
      </Grid>
    );
  };
  console.log("Rendering FeeSummary");
  return props.isSellPage ? sellPageFees() : buyPageFees();
};

1 个答案:

答案 0 :(得分:1)

对于遇到同样问题的任何人,我设法通过独立于更新字段所需的计算来处理状态更新来解决问题,请参见以下代码:

BuyScreen.js

<CurrencyWidget
   currencyName={balancesMock.values.currencyBalances[0].name}
   currencyCode={balancesMock.values.currencyBalances[0].code}
   balance={balancesMock.values.currencyBalances[0].total}
   inputAmount={buySourceAmount}
   setInputAmount={handleBuySourceAmount}
   autofocus
/>

和handleBuySourceAmount函数:

const handleBuySourceAmount = (amount) => {
    const _feeAmount = calculateFees(amount);
    const _subTotalAmount = calculateSubtotal(amount, _feeAmount);
    const _totalBuyAmount = calculateTotalBuyTransactionAmount(
      _subTotalAmount,
      cryptoBuyPrice
    );

    setBuySourceAmount(amount);
    setFeeAmount(_feeAmount);
    setFeeSubTotalAmount(_subTotalAmount);
    setBuyDestinationAmount(_totalBuyAmount);
  };