上下文 API 与本地存储是 apples vs oranges comparison。
Context API 用于在组件树中共享状态。
上下文提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递道具。
Local Storage 用于在会话之间存储数据。
只读的 localStorage 属性允许您访问文档来源的 Storage 对象; 存储的数据跨浏览器会话保存。
正确的比较可能是 Local Storage vs Cookies,上下文 API 与状态管理库(不是真的,因为 Context is not a state management tool)。
虽然您可以将所有内容存储在本地存储中(尽管它不可扩展和可维护),但它并没有什么用处。
它不会有用,因为你不能通知你的组件状态变化,你需要使用任何 React 的 API。
本地存储通常用于会话功能,例如保存用户设置、喜爱的主题、身份验证令牌等。
通常,您在应用程序启动时从本地存储读取一次,并使用自定义挂钩更新其相关数据更改的键。
这是useLocalStorage 自定义挂钩的有用收据:
function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
try {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = value => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore =
value instanceof Function ? value(storedValue) : value;
// Save state
setStoredValue(valueToStore);
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
return [storedValue, setValue];
}