Tsu*_*chi 0 javascript reactjs react-hooks
我目前正在学习 React。
我可以在函数组件中使用“let”而不是“useState”吗?
const Func = () => {
let fruit = "banana";
const changeFruit = () => {
fruit = "apple"
};
changeFruit();
}
Run Code Online (Sandbox Code Playgroud)
const Func = () => {
const [fruit, setFruit] = useState("banana");
const changeFruit = () => {
setFruit("apple");
};
changeFruit();
}
Run Code Online (Sandbox Code Playgroud)
那不是函数式组件,因为函数式组件必须返回一个 React 元素。
如果它是一个功能组件,并且您在返回 Element 之前同步更改变量,那很好:
const Func = () => {
let fruit = "banana";
const changeFruit = () => {
fruit = "apple"
};
changeFruit();
return <>{fruit}</>; // displays "apple"
};
Run Code Online (Sandbox Code Playgroud)
如果您异步更改它,例如
setTimeout(changeFruit, 1000);
Run Code Online (Sandbox Code Playgroud)
那么在变量更改后组件将不会重新渲染。这不是你通常想要的。如果您useState调用该setFruit函数,则组件会重新渲染。
| 归档时间: |
|
| 查看次数: |
2381 次 |
| 最近记录: |