Creates a stateful value that is persisted to sessionStorage
, and a function to update it.
- Use the
useState()
hook with a function to initialize its value lazily. - Use a
try...catch
block andStorage.getItem()
to try and get the value fromWindow.sessionStorage
. If no value is found, useStorage.setItem()
to store thedefaultValue
and use it as the initial state. If an error occurs, usedefaultValue
as the initial state. - Define a function that will update the state variable with the passed value and use
Storage.setItem()
to store it.
代码实现
const useSessionStorage = (keyName, defaultValue) => {
const [storedValue, setStoredValue] = React.useState(() => {
try {
const value = window.sessionStorage.getItem(keyName);
if (value) {
return JSON.parse(value);
} else {
window.sessionStorage.setItem(keyName, JSON.stringify(defaultValue));
return defaultValue;
}
} catch (err) {
return defaultValue;
}
});
const setValue = newValue => {
try {
window.sessionStorage.setItem(keyName, JSON.stringify(newValue));
} catch (err) {}
setStoredValue(newValue);
};
return [storedValue, setValue];
};
使用样例
const MyApp = () => {
const [name, setName] = useSessionStorage('name', 'John');
return <input value={name} onChange={e => setName(e.target.value)} />;
};
ReactDOM.createRoot(document.getElementById('root')).render(
<MyApp />
);
翻译自:https://www.30secondsofcode.org/react/s/use-session-storage