首页 > 解决方案 > 如果 -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);
    }
    
  };

标签: reactjsdebuggingreact-context

解决方案


推荐阅读