在AngularJS中,我看到这样的变化。
$scope.$watch("rateMode",
function (newVal, oldVal) {
if (newVal != oldVal && timeRange != "") {
if (typeof $scope.onRateCallback != undefined) {
$scope.onRateCallback($scope.chartDataObject, newVal);
}
updateChart(timeRange);
}
},
true
);
我如何在ReactJS中做到这一点?
要在组件渲染时观察React中的变化,可以使用useEffect钩子
useEffect有两个参数,第一个是回调函数,第二个是依赖数组。
在回调函数中,当这个useEffect运行时,你要写你想做的事情。在依赖数组中,你传递state或props,当依赖数组中传递的变量发生变化时,它会再次运行useEffect。
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Here, useEffect runs on first render and after whenever count is changed
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
从问题来看,您需要根据代码中的更改更新ui。请尝试在React中使用useState。
const [rateMode, setRateMode] = useState();
并使用rateMode变量进行渲染。当setRateMode被调用并且速率模式被更新时,UI将呈现更改。
如果你有一个变量或useState并且想要查看它,请使用
useEffect hook