React Context API与本地存储 [英] React Context Api vs Local Storage

查看:144
本文介绍了React Context API与本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于上下文API和本地存储,我有一些困扰我的一般问题.

I have some general questions which are bothering me regarding the context API and local storage.

何时使用本地存储?何时使用Context API?何时使用两者?

When to use local storage?, when to use the Context API and when would I use both?

我知道要在刷新后保留数据,我需要诸如本地存储或会话存储之类的东西,那么我是否要完全放弃上下文API并将所有内容存储在本地存储中?这样,我不仅可以存储数据,还可以保持刷新状态?一些见识会真的很有帮助.

I know that to persist data after the refresh I need something like local storage or session storage, so do I ditch the context API entirely and just store everything in the local storage? this way I can not only store data but also keep it on refresh? some insight would be really helpful.

有什么优点和缺点?

推荐答案

上下文API与本地存储的比较是苹果与橙子比较.

Context API vs Local storage is apples vs oranges comparison.

上下文API 适用于共享状态组件树.

Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递 props.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

本地存储用于在会议.

只读的localStorage属性允许您访问文档来源的存储对象;存储的数据在浏览器会话中保存.

正确的比较可能是 本地存储与Cookies ,上下文API与状态管理库(并非如此,因为上下文不是状态管理工具).

The right comparison might be Local Storage vs Cookies, Context API vs State-Management Library (not really, since Context is not a state management tool).

虽然您可以将所有内容存储在本地存储中(尽管它不具有可伸缩性和可维护性),但这将无济于事.

While you can store everything on the local storage (although it's not scalable and maintainable) it won't be useful.

这将不会有用,因为您无法在状态更改时通知组件,您需要为此使用任何React的API.

It won't be useful because you can't notify your components on state change, you need to use any React's API for it.

通常,本地存储用于会话功能,例如保存用户设置,收藏的主题,身份验证令牌等.

Usually local storage is used for session features like saving user settings, favorite themes, auth tokens, etc.

通常,您在应用程序启动时从本地存储中读取一次,并使用自定义钩子在相关数据更改时更新其键.

And usually, you read once from local storage on application start, and use a custom hook to update its keys on related data change.

以下是 useLocalStorage 自定义钩子的有用收据:

Here is a helpful receipt for useLocalStorage custom 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];
}

这篇关于React Context API与本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆