如何解决React Rerenderign问题
具有总和函数和总和作为使用效应的依赖性。每当输入更改Console.log(“ sum as as”)打印时。 Console.log(“ sum is is”)即使输入更改也没有依赖性,也不会打印。这是因为当输入更改时,它将分配给组件和总和函数地址,这是为什么它触发使用效应或可能不同的原因。
import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
const [num1] = useState(4);
const [num2] = useState(5);
const [input, setInput] = useState();
const sum = () => num1 + num2;
useEffect(() => {
console.log("sum is");
}, [num]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input onChange={(e) => setInput(e.target.value)} />
</div>
);
}
have sum function and sum as dependency of useEffect. whenever the input change console.log("sum is") printed. console.log("sum is") is not printed when there is no dependency in useEffect even if input change. it is because of when input change it rerender the component and sum function address will be assign to different thats why it trigger the useEffect or may be different.
import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
const [num1] = useState(4);
const [num2] = useState(5);
const [input, setInput] = useState();
const sum = () => num1 + num2;
useEffect(() => {
console.log("sum is");
}, [num]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input onChange={(e) => setInput(e.target.value)} />
</div>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用效应是用于制作某种共同调整的React钩子
useEffect is a React hook used to make some kind of co-routines, it is triggered when it dependencies are updated or when the component is rendered
原因
console.log(“ sum is”)
在每个渲染上执行是因为sum
:
在您的情况下
const sum =()=&gt; NUM1 + NUM2
在每个渲染上都有不同的值重新分配,并且useffect
识别sum
的值已更改。要解决问题,您可以:
sum
为值:cosnt sum = num1 + num1 + num2
usecallback
用于记忆的挂钩该函数(换句话说,该函数将存储在内存中,因此在每个渲染中都相等),只要NUM1和NUM2未分配新值,
sumcallback
将具有相同每次价值The reason
console.log("sum is")
is executed on every render is becausesum
is a function and not a value, and when a function is compared to another function, even if its defined exactly the same way, the equality operator will return falseFor example:
In your case
const sum = () => num1 + num2
is reassigned with a different value on each render, anduseEffect
identifies that the value ofsum
had changed.To solve the problem, you can:
sum
as a value:cosnt sum = num1 + num2
useCallback
hook which is used to memoize the function (in other words, the function will be stored in memory and therefore be equal in each render)Now, as long as num1 and num2 aren't assigned with new values,
sumCallback
will have the same value each time