首页 > 解决方案 > React:组件中用于计算奖励积分的函数不起作用

问题描述

我正在尝试在 RewardsCard 组件中编写一个函数来计算客户购买时获得的奖励积分。但是,出现了一些错误,我无法弄清楚出了什么问题。

这是在其代码中调用 RewardsCard 的购买月份组件:

import React, { Component } from 'react';
import RewardsCard from "./RewardsCard";

export default class purchaseMonth extends Component {
  constructor(props) {
    super(props);
      this.state = {
        transitionArr: this.props.transitions
    };
  }

  render() {
    const transitionList = this.state.transitionArr;
    return (
      <div>
        <h2>{this.props.month}</h2>
        <div>
        {transitionList.map((eachTransition, i) => (
          <RewardsCard
          {...eachTransition}
          key={eachTransition.id}
          purchased={eachTransition.purchase}
          />
        ))}
        </div>
      </div>
    )
  }
}

还有奖励卡本身

import React, { Component } from 'react'

export default class RewardsCard extends Component {
  constructor(props) {
    super(props);
      this.state = {
        purchaseN: this.props.purchased,
        rewards1: 0,
        rewards2: 0
    };
  }

  calculateRewards = () => {
    // console.log("purchasereward", this.state.purchaseN);
    let purchasedT = this.props.purchased;
    if(50 < purchasedT && purchasedT < 100) {
      let getRewards1 = purchasedT - 50;
      this.setState ({
        rewards1: getRewards1
      })
    }
    if(purchasedT > 100) {
      let getRewards2 = (purchasedT - 100) * 2;
      this.setState({
        rewards2: getRewards2
      })
    }
    let totalRewards = this.state.rewards1 + this.state.rewards2
    return totalRewards;
  }

  render() {    

    return (
      <div>
        <p>{this.props.date}</p>
        <p>{this.props.purchase}</p>
        <p>{this.calculateRewards()}</p>
      </div>
    )
  }
}

我得到的错误是"Warning: Cannot update during an existing state transition (such as within 渲染). Render methods should be a pure function of props and state."

标签: reactjsfunction

解决方案


作为警告状态,您正在设置渲染函数内的状态。

从您的代码中,您不需要设置状态,您可以计算值并返回它,这将在渲染中显示。

您可以更改 calcualteRewards 函数,如下所示

  calculateRewards = () => {
    // console.log("purchasereward", this.state.purchaseN);
    let purchasedT = this.props.purchased;
    let totalRewards = 0;
    if(50 < purchasedT && purchasedT < 100) {
      let getRewards1 = purchasedT - 50;
        totalRewards += getRewards1;
    }
    if(purchasedT > 100) {
      let getRewards2 = (purchasedT - 100) * 2;
      totalRewards += getRewards2;
    }

    return totalRewards;
  }

推荐阅读