reactjs - 仅在状态更改时才尝试运行功能
问题描述
只有当小时的状态发生变化时,我才想运行 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>
);
};
解决方案
自从我使用更新的 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>
);
}
推荐阅读
- spring-boot - 如何使用 EmbeddedKafkaRule/EmbeddedKafka 设置 Spring Kafka 测试以修复 TopicExistsException 间歇性错误?
- svelte - Sapper 默认模板的汇总配置
- scaling - 为什么我们只在缩放问题的训练数据中使用 fit() 方法?
- python - 如何在同一图上正确绘制个别年份的月度数据
- performance - 带递归的while循环的时间复杂度
- react-native - React Native Firebase Storage - 尝试使用 .putFile() 保存图像时出错
- google-api - Google Calendar API - 如何保存/使用 StoredCredentials?
- java - 使用主要活动中的按钮更改第二个活动的颜色=崩溃
- python - Python Text Clean 删除超链接
- javascript - Rails + Rspec:由于 Vue.js 页面中的 Javascript 'unsafe-eval' 导致测试失败