首页 > 解决方案 > 仅在状态更改时才尝试运行功能

问题描述

只有当小时的状态发生变化时,我才想运行 set totals 函数。它在每次安装组件时运行,而不是仅在值更改时运行。this.state 是一个非常大的上下文文件的一部分,所以我只粘贴了正在使用的函数

context.js (Class Component)
set Total
        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);
            }
    This is my component tha
     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 pCR = useContext(ProductContext);
        const prevCountRef = useRef();
    
    
        useEffect(() => {
          alert('Run')
          console.log(pCR.hours, 'Final Quote Run', pCR.total);
          pCR.setTotal();
          console.error(pCR.hours);
      }, [pCR.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(pCR.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"
              />
              {pCR.activeAddOns.map((service, index) => (
                <Badge color="info" pill>
                  {service.title}
                </Badge>
              ))}
            </div>
          </Container>
        </section>
      );
    };

标签: reactjsreact-hooks

解决方案


自从我使用更新的 React 功能以来已经有一分钟了,但是我什么时候可以useEffect在我的功能组件中使用。第二个参数是您要监视更改的变量。如果您不提供第二个参数,它将类似于 componentDidMount 和 componentDidUpdate 运行。可能使用的示例:

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  const [test, setTest] = useState('');

  // Specify to watch count because we have more than one state variable
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

这是他们的一些文档:https ://reactjs.org/docs/hooks-effect.html


推荐阅读