我有一些关于上下文 API 和本地存储的一般性问题困扰着我。
何时使用本地存储?何时使用 Context API 以及何时使用两者?
我知道要在刷新后保留数据,我需要本地存储或 session 存储之类的东西,所以我是否完全放弃上下文 API 并将所有内容存储在本地存储中?这样我不仅可以存储数据,还可以保持刷新?一些见解会非常有帮助。
有哪些优点和缺点?
最佳答案
上下文 API 与本地存储是 apples vs oranges comparison .
Context API用于 共享状态 在组件树中。
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Local Storage用于在 session 之间存储数据。
The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
正确比较可能是 Local Storage vs Cookies , 上下文 API 与状态管理库(不是真的,因为 Context is not a state management tool )。
虽然您可以将所有内容存储在本地存储中(尽管它不可扩展和可维护),但它并没有用处。
它不会有用,因为 您无法在状态更改时通知您的组件 ,你需要为它使用任何 React 的 API。
通常本地存储用于 session 特点 比如保存用户设置、喜欢的主题、身份验证 token 等。
通常,您会阅读 一次从应用程序启动时的本地存储,并使用自定义 Hook 更新其相关数据更改的键。
这是
useLocalStorage
的有用食谱自定义钩子(Hook):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];
}
关于javascript - React Context Api 与本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62105880/