admin管理员组文章数量:1318015
In AngularJS, I watch change like this.
$scope.$watch("rateMode",
function (newVal, oldVal) {
if (newVal != oldVal && timeRange != "") {
if (typeof $scope.onRateCallback != undefined) {
$scope.onRateCallback($scope.chartDataObject, newVal);
}
updateChart(timeRange);
}
},
true
);
How can I do it in ReactJS?
In AngularJS, I watch change like this.
$scope.$watch("rateMode",
function (newVal, oldVal) {
if (newVal != oldVal && timeRange != "") {
if (typeof $scope.onRateCallback != undefined) {
$scope.onRateCallback($scope.chartDataObject, newVal);
}
updateChart(timeRange);
}
},
true
);
Share Improve this question asked Jun 14, 2022 at 4:35 Khoa NguyenKhoa Nguyen 151 silver badge4 bronze badges 2How can I do it in ReactJS?
- Can you elaborate more ? – Aman Sadhwani Commented Jun 14, 2022 at 4:41
- 1 useEffect hook in React can be used to watch a state variable. – subodhkalika Commented Jun 14, 2022 at 4:42
2 Answers
Reset to default 6For watching changes in React while ponent is rendering you can use useEffect hook
useEffect takes two arguments first is callback function and second is dependency array.
In callback function you write what you want to do whenever this useEffect runs. And in dependency array you pass state or props, and whenever the passed variables in the dependency array changes it runs the useEffect again.
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>
);
}
From the question it looks like you need to update the ui as per changes in the code. Please try using a useState in React.
const [rateMode, setRateMode] = useState();
and use the rateMode variable for rendering. When the setRateMode is called and rate mode gets updated the UI will render the changes.
if You have a variable or useState and want to watch that please use
useEffect hook
本文标签: javascriptHow to watch changes in reactjsStack Overflow
版权声明:本文标题:javascript - How to watch changes in react.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742037934a2417403.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论