【问题标题】:Chaining React.useEffect dependencies results in slow re-rendering链接 React.useEffect 依赖项会导致重新渲染缓慢
【发布时间】:2020-11-16 15:05:01
【问题描述】:

我正在创建一个“购买”加密货币的屏幕,并且我已经按照所附图像组织了组件。当我更改欧元输入金额时,我希望计算能够非常快地完成,因为不涉及任何 API 调用(只是基本的数学运算)。由于我将 useEffect 状态和更新函数从 BuyScreen 传递到 CurrencyWidget 和 FeeSummary 作为道具,我需要使用(据我所知)useEffect 和对值的依赖以确保我有最后更新的一个。

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

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();
};

【问题讨论】:

  • 您是否尝试过使用 HOC 有点状态管理来查看它是如何工作的?类似于来自父级的 onChange 函数来管理状态而不是使用 useEffects 以便您直接立即更改状态而不是等待 React 意识到它需要使用新数据重新渲染这些组件?编辑:您还可以考虑使用 React 中的 useReducer 之类的东西,并为这些组件创建自己的小型 Redux,例如 statemanager 以及上下文。
  • 我想我通过了你的建议,谢谢!查看答案

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


【解决方案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);
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 2018-12-03
    • 2021-10-28
    • 2022-10-04
    • 2022-11-22
    • 2010-12-29
    • 2021-01-17
    相关资源
    最近更新 更多