刷新页面时反冲不持久状态

Recoil not persisting state, when refreshing page

我有一些 React 反冲状态,但是每当手动刷新页面时,反冲状态都会重置。

这是正常行为吗,因为我知道 fluxreact-redux 等其他状态管理库也会这样做。

最好的做法是将它保存到 localStorage 中以实际保留在浏览器中(因为 localStorage 也是同步的 api,所以这肯定也会导致一些问题。)

即使它是一个相当新的库,是否有一些方法可以在手动页面刷新时保持状态?

I have some state with React recoil, but whenever the page is manually refreshed, the recoil state is reset.

是的,这是正常行为。

Is this normal behavior because I know other state management libraries like flux and react-redux will do this.

是的,只有一部分状态管理库会保留数据本身。更常见的是找到执行此操作的外部库或自定义解决方案。

Is it best practice to save it into localStorage to actually have it persisted in the browser (because localStorage is also asynchronous API, so that could definitely also cause some issues.)

这取决于您的需求:

  • 您想提供完整的离线体验吗?加油
  • 您是否担心数据量大时对性能的影响?你可以考虑indexedDB
  • 您只是想保留一些身份验证令牌吗?可能 sessionStorage 可能是正确的解决方案
  • 服务器是否需要知道存储的数据?您可以选择 cookies

假设在不知道您的用例的情况下很难提出建议

Even though it is a fairly new library, is there some way to persist state even on manual page refreshes?

是的,使用 useRecoilTransactionObserver_UNSTABLE you could get notified of every Recoil change and persisting the data. Then, with RecoilRoot' initializeState 您可以恢复它。正如您所说,该库是新的,API 可能会在接下来的几个月内快速变化

这很好用,来自文档 here

对订单状态的任何更改都会写入 localStorage,并且在刷新时将 localStorage 中的值读入订单状态。

// define this function somewhere
const localStorageEffect = key => ({setSelf, onSet}) => {
  const savedValue = localStorage.getItem(key)
  if (savedValue != null) {
    setSelf(JSON.parse(savedValue))
  }
  onSet(newValue => {
    localStorage.setItem(key, JSON.stringify(newValue))
  })
}

// this is an example state atom
export const orderState = atom({
  key: 'orderState',
  default: {
    store: {}, // { id, name, phone, email, address }
    items: {}, // { [itemId]: { id, name, sizeTable, quantity, size } }
    contact: { deliveryOption: 'ship' }, // { name, email, phone, address, city, state, zipcode, promotions, deliveryOption }
  },
  // add these lines to your state atom, 
  // with the localStorage key you want to use
  effects_UNSTABLE: [
    localStorageEffect('order'),
  ],
})

您可以使用 recoil-persist 库将状态保存到 localStorage。

在这里你可以如何使用它:

import { recoilPersist } from 'recoil-persist'

const { persistAtom } = recoilPersist()

const counterState = atom({
  key: 'count',
  default: 0,
  effects_UNSTABLE: [persistAtom],
})