【问题标题】:variables are not reassigning after running useEffect运行 useEffect 后变量未重新分配
【发布时间】:2020-05-21 10:44:52
【问题描述】:

所以我在开头定义了这两个元素

let interestElm = (
    <Row
      title={translate('calculator.interest')}
      value={translate('currency_amount', {
        amount: offer.totalInterest,
      })}
    />
  );
  let commisionElm = (
    <Row
      title={translate('calculator.commission')}
      value={translate('currency_amount', {
        amount: offer.newInitialCommission,
      })}
    />
  ); 

那么在渲染页面的时候useEffect会运行这个函数

useEffect(()=>{
    discountElemHandler(discountData)
  }, [discountData, amount])

这个函数检查一些值并且它们存在应该重新分配变量

const discountElemHandler = (discount) => {
    if (discount.length) {
      discount.forEach(discountItem => {
        if (discountItem.type === 'Type1') {
          interestElm = (
            <Row
              inheritStyle={style.discount}
              title={translate('calculator.interest')}
              discount={translate('currency_amount', {
                amount: offer.newInterest + discountItem.amount,
              })}
              value={translate('currency_amount', {
                amount: offer.totalInterest,
              })}
            />
          );
        }

        if (discountItem.type === 'Type2') {
          commisionElm = (
            <Row
              inheritStyle={style.discount}
              title={translate('calculator.commission')}
              discount={translate('currency_amount', {
                amount: offer.newInitialCommission + discountItem.amount,
              })}
              value={translate('currency_amount', {
                amount: offer.newInitialCommission,
              })}
            />
          );
        }
      });
    }
  };

我可以在调试器上看到该函数满足条件,但由于某种原因,重新分配没有发生?

任何人都可以帮助我吗? 谢谢加载

【问题讨论】:

  • @JaredSmith 问题不在于状态,因为元素中的大部分数据都是从状态渲染的,所以它应该在它发生变化时自动调用重新渲染,但即使我把整个榆树在状态我仍然面临同样的问题!
  • 如果您提供 RENDER 方法会很有用,这样我们就可以看到您实际渲染 JSX 的内容/方式
  • @LamisAbouzina 您正在尝试修改封闭变量而不是放入状态,这意味着它是另一个的副本。

标签: javascript react-native react-hooks


【解决方案1】:

在 render 方法在屏幕上完成绘制后调用 useEffect。这意味着如果您希望触发新的渲染,在 useEffect 运行后,您需要触发状态更改。 我建议您应该将两个 let 变量定义为 STATE,或者您应该在状态中存储一些其他类型的数据,这些数据将在这两个变量中使用。

【讨论】:

  • 其实offer、discount、discountData等部分元素几乎都来自几个州
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 2022-12-31
  • 1970-01-01
相关资源
最近更新 更多