如何从localStorage获取一个键的值,并把它的钩子输入?



对不起,我才刚刚开始学钩子。我不能正确地写它:在页面加载时,必须从localStorage中获取键appData的值,并将其放在输入中。

import './App.css';
import { useState, useEffect } from 'react';
export default function App() {
const [appData, setValue] = useState('');

useEffect(() => localStorage.setItem('appData', appData), [appData]);

return (
<div>
React Marathon, appData: <input size='5' defaultValue={appData}></input>
</div>
);
}

将初始值设置为localStorage值

const [appData, setValue] = useState(localStorage.getItem('appData') || '')
import './App.css';
import { useState, useEffect } from 'react';
export default function App() {  
const [appData, setValue] = useState("");
useEffect(() => {
if(!localStorage.getItem('appData')) {
localStorage.setItem('appData', appData)
}
}, []);
useEffect(() => setValue(localStorage.getItem('appData')), []);
return (
<div>
React Marathon, appData: <input size='5' defaultValue={appData}></input>
</div>
);
}

相关内容

  • 没有找到相关文章

最新更新