redux-persist+ts简单示例react项目中
下面是一个使用redux-persist和TypeScript的简单示例:
// 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 组件使用了 useSelector 和 useDispatch 两个 React Redux 的 hooks,它们需要从 @types/react-redux 包中导入。如果你的项目中已经安装了 @types/react-redux,则无需额外安装。如果没有安装,则可以使用以下命令进行安装:
npm install --save-dev @types/react-redux
希望这个简单示例能够帮助你理解如何在使用 TypeScript 的 React 项目中使用 redux-persist
原文地址: http://www.cveoy.top/t/topic/iU3c 著作权归作者所有。请勿转载和采集!