reactjs - 如果 -hours 变量已更改,我如何获得此使用效果/功能仅运行
问题描述
我正在从事个人/商业项目。我试图在我的网站上给客户报价。有一个添加包和插件的选项。加载 finalquote 组件后,它会根据存储在我的上下文文件中的小时数作为 this.state.hours 计算总数。
我遇到的问题是即使时间改变了它也会运行计算。例如,当我单击管理仪表板插件并转到下一页时,它会在我重新安装组件时添加数量,即使我没有更改或向变量添加任何时间,它也会添加相同的数量。
import React, { useState, useEffect, useContext, useRef } from 'react';
import { ProductContext } from '../pages/oniContext';
import { Container, Badge } from 'reactstrap';
import {
Subtitle,
Description,
Titlespan2,
} from '../components/common/title/index';
import { total } from '../components/total';
export const FinalQuote = () => {
const { hours, setTotal,total,activeAddOns, } = useContext(ProductContext);
const prevCountRef = useRef();
useEffect(() => {
alert('Run');
console.log(hours, 'Final Quote Run', total);
setTotal();
console.error(hours);
}, [hours]);
return (
<section className="testimonial-wrapper gradient-color" id="testimonial">
<Container>
<div className="main-title-wrapper">
<Subtitle Class="site-subtitle gradient-color" Name="Your Quote" />
<Titlespan2
Class="sitemain-subtitle"
Name={`$${Math.round(total)}`}
/>
<Description
Class="site-dec"
Name="The Shown Price is only an estimate and may increase or decrease based on demand and extent of work"
/>
{activeAddOns.map((service, index) => (
<Badge color="info" pill>
{service.title}
</Badge>
))}
</div>
</Container>
</section>
);
};
上下文设置总功能
setTotal = () => {
if (this.state.hours > 0) {
this.setState((prevState) => {
if (prevState.hours === this.state.hours) {
console.log(prevState.hours);
}
return {
total: this.state.total + this.state.hours * ratePerHour * Math.PI,
};
});
console.log(this.state.total, '+', this.state.hours, '*', ratePerHour);
}
};
解决方案
推荐阅读
- postgresql - 如何将属性设置为其默认值
- reactjs - 在 useState 的调度中使用未声明的字段时如何获取打字稿错误
- opencv - 如何在 OpenCV Mat 上使用 RealSense 的 spatial_filter?
- firebase - Firebase:用于无密码身份验证的动态链接;不接受 Google 提供的域
- terraform - 具有嵌套地图列表的 Terraform 模块计数
- camera - 使用专有安装程序捆绑 OBS (https://obsproject.com/)
- kvm - kvm 为虚拟机添加带宽限制
- node.js - 如何正确模拟单元测试的数据对象?
- sql - 使用 cubeSQL 尝试将数据添加到表中的问题
- swift - 错误:在调用中传递了额外的尾随闭包 - NavigationLink