我正在学习 React 和 localStorage。然后,我看到一篇文章说由于副作用,localStorage 最好通过 useEffect() 使用。所以,这段代码很糟糕:
import React from 'react';
const App = () => {
const [value, setValue] = React.useState('');
const onChange = event => {
localStorage.setItem('myValueInLocalStorage', event.target.value);
setValue(event.target.value);
};
return (
<div>
<h1>Hello React with Local Storage!</h1>
<input value={value} type="text" onChange={onChange} />
<p>{value}</p>
</div>
);
};
export default App;
Run Code Online (Sandbox Code Playgroud)
但是这段代码是对的:
import React from 'react';
const App = () => {
const [value, setValue] = React.useState('');
React.useEffect(() => {
localStorage.setItem('myValueInLocalStorage', value);
}, [value]);
const onChange = event => setValue(event.target.value);
return (
<div>
<h1>Hello React with Local Storage!</h1>
<input value={value} type="text" onChange={onChange} />
<p>{value}</p>
</div>
);
};
export default App;
Run Code Online (Sandbox Code Playgroud)
一问为什么?为什么第一个代码有问题,第二个代码使用 useEffect() 有什么好处
Bho*_*yar -2
使用useEffect的好处是可以在不需要的时候进行清理。
React.useEffect(() => {
localStorage.setItem('myValueInLocalStorage', value);
return (() => { // clean up
// remove when unnecessary
if (true) { // your condition
localStorage.removeItem('myValueInLocalStorage');
// Or even set empty value
}
});
}, [value]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
612 次 |
| 最近记录: |