为什么函数getSth
在每次组件重现时都会被调用(可以看到console.log
)(通过点击按钮改变isSth
的值),尽管它没有改变randomValue
的状态?
import React, { useState } from 'react';
function getSth() {
console.log('init');
return Math.random();
}
function Home() {
const [randomValue, setRandomValue] = useState(getSth());
const [isSth, setIsSth] = useState(false);
console.log(randomValue);
const onClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setIsSth((prev) => !prev);
};
return (
<button type="button" onClick={onClick}>
Click me
</button>
);
}
export default Home;
但当我这样做的时候,getSth
实际上是一次呼叫?
const [randomValue, setRandomValue] = useState(0);
useEffect(() => {
getSth();
}, []);