📅  最后修改于: 2022-03-11 15:03:53.294000             🧑  作者: Mango
const useLocalStorage = (keyName, defaultValue) => {
const [storedValue, setStoredValue] = React.useState(() => {
try {
const value = window.localStorage.getItem(keyName);
if (value) {
return JSON.parse(value);
} else {
window.localStorage.setItem(keyName, JSON.stringify(defaultValue));
return defaultValue;
}
} catch (err) {
return defaultValue;
}
});
const setValue = newValue => {
try {
window.localStorage.setItem(keyName, JSON.stringify(newValue));
} catch (err) {}
setStoredValue(newValue);
};
return [storedValue, setValue];
};
Example
const MyApp = () => {
const [name, setName] = useLocalStorage('name', 'John');
return setName(e.target.value)} />;
};
ReactDOM.render( , document.getElementById('root'));