这是一个使用 redux-persist 和 TypeScript 的简单示例,展示了如何在 React 项目中将 Redux store 中的数据持久化到本地存储。

// store.ts

import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

import rootReducer from './reducers';

const persistConfig = {
  key: 'root',
  storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = createStore(persistedReducer);
export const persistor = persistStore(store);
// reducers.ts

import { combineReducers } from 'redux';

const initialState = {
  count: 0,
};

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}

const rootReducer = combineReducers({
  counter: counterReducer,
});

export default rootReducer;
// Counter.tsx

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

const Counter = () => {
  const count = useSelector((state) => state.counter.count);
  const dispatch = useDispatch();

  const increment = () => {
    dispatch({ type: 'INCREMENT' });
  };

  const decrement = () => {
    dispatch({ type: 'DECREMENT' });
  };

  return (
    <div>
      <button onClick={decrement}>-</button>
      <span>{count}</span>
      <button onClick={increment}>+</button>
    </div>
  );
};

export default Counter;
// App.tsx

import React from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';

import Counter from './Counter';
import { store, persistor } from './store';

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <Counter />
      </PersistGate>
    </Provider>
  );
};

export default App;

在上述示例中,store.ts 文件创建了一个包含 redux-persist 的 Redux store,并将其导出为 store 和 persistor。reducers.ts 文件定义了一个简单的 counter reducer,并将其组合成根 reducer。Counter.tsx 文件使用 useSelector 和 useDispatch 从 Redux store 中获取状态和分发动作。最后,App.tsx 文件使用 Provider 和 PersistGate 包裹应用组件,以便提供 Redux store 和持久化功能。

请注意,Counter 组件使用了 React Redux 的 useSelector 和 useDispatch 两个 hooks,需要从 @types/react-redux 包中导入。如果项目中已经安装了 @types/react-redux,则无需额外安装。如果没有安装,则可以使用以下命令进行安装:

npm install --save-dev @types/react-redux

希望这个简单示例能够帮助你理解如何在使用 TypeScript 的 React 项目中使用 redux-persist。

Redux-Persist 与 TypeScript 结合:React 项目中的持久化数据示例