reactjs - 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."
解决方案
作为警告状态,您正在设置渲染函数内的状态。
从您的代码中,您不需要设置状态,您可以计算值并返回它,这将在渲染中显示。
您可以更改 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;
}
推荐阅读
- authentication - Google Cloud Endpoints pass API key in header
- javascript - Print table information after onclick event in Django
- docker-compose - How can I use docker-compose in a bitbucket pipeline to deploy to a remote host?
- python - Random number generation in Tensorflow is very slow (tensorflow-gpu)
- excel - How to convert time stamp with text into a date
- java - Apache Artemis 客户端故障转移发现
- flutter - Where is the best place to put your ChangeNotifierProvider?
- spring-boot - The Maven Command With spring-boot:spring-image Doesn't Work As What It Should Do
- ios - iOS 应用程序在更改已撤销的隐私设置后重新启动
- python - 推荐一次替换张量中的多个值的方法?