I have a very simple question which has been bugging me. I am relatively new to react and having issues with state. If I have a component that creates a state variable like below
const [state, setState] = useState(null)
and let in the code I do something like this...
setState(50)
Changing the state forces a re-render which in turn re-initializes the state variable as null. What am I doing wrong? I want the app the re-render when state changes and leave state as 50 in this example but when it re-renders it re-initializes the state as null. Super strange.
actual code...
const ConnectBackend = props => {
const [moisture, setMoisture] = useState(null)
let temp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var i = 0;
function myLoop() {
setTimeout(function() {
setMoisture(temp[i]);
console.log(moisture)
i++;
if (i < 10) {
myLoop();
}
}, 3000)
}
myLoop();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…