[英]Why i am getting this error: variable from inside React Hook useEffect will be lost after each render?
i am getting this error warning Assignments to the 'height' variable from inside React Hook useEffect will be lost after each render.我收到此错误警告分配给 React Hook useEffect 内部的“高度”变量将在每次渲染后丢失。 To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property.
要随着时间的推移保留该值,请将其存储在 useRef Hook 中并将可变值保留在“.current”属性中。 Otherwise, you can move this variable directly inside useEffect react-hooks/exhaustive-deps
否则,您可以直接在 useEffect react-hooks/exhaustive-deps 中移动此变量
this is my code这是我的代码
what happen?发生什么事?
const MyComponent = ({
height,})=>{
useEffect(() => {
const getData = async () => {
try {
if (height < 10) {
height = 10
}
const newValue = calculateValue(height, width)
}
if(isNotValidate){
getData()
}
}
by the error i am using useEffect but the error following apparing由于我正在使用 useEffect 的错误,但出现以下错误
In React, state and props are to be considered and treated as immutable.在 React 中,state 和 props 被认为是不可变的。 When you set
height = 10
this mutates the props object.当您设置
height = 10
时,这会改变道具 object。 The error is saying that each render that the height
prop is reset to the passed value.错误是说每个渲染
height
道具都重置为传递的值。
I just want to set new value if the current value is less to 10, and then calculateValue
如果当前值小于10,我只想设置新值,然后calculateValue
You can use the maximum of height
or the value 10.您可以使用最大
height
或值 10。
const newValue = calculateValue(Math.max(height, 10), width)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.