基本依赖
# 基本依赖
npm install redux redux-thunk react-redux
Redux结构构建
基础示例,增加减少count
action:src/redux/action.ts
export const ActionTypes = {
INCREMENT: 'INCREMENT',
DECREMENT: 'DECREMENT',
};
reducer:src/redux/reducer.ts
注意点:这里 reducer 一定要保证返回 preState,因为在 createStore 初始化的时候,会调用一次 reducer,switch..case..default,要有默认返回值,否则 store.getState() 为 undefined
import { ActionTypes } from './action';
import { Reducer } from 'redux';
export const initState = {
count: -1,
};
export type ReduxState = typeof initState;
type ReduxAction = {
type: string;
payload: any;
}
export const reducer = (state: ReduxState | undefined, action: ReduxAction): ReduxState => {
if (state === undefined) return initState;
const { type, payload } = action;
switch (type) {
case ActionTypes.INCREMENT:
return { count: state.count + payload };
case ActionTypes.DECREMENT:
return { count: state.count - payload };
default:
return state;
}
};
store:src/redux/store.ts
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { reducer } from './reducer';
export const store = createStore(reducer, applyMiddleware(thunk));
整合 react-redux
1.外部Provider包裹
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { store } from './redux/store';
import { Provider } from 'react-redux';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root'),
);
2.内部组件操作数据
import { useSelector } from 'react-redux';
// 获取store值
const count = useSelector(s: StoreState => s.count);
// 通过dispatch操作store,两种获取Dispatch方式,效果一样
const dispatch = useDispatch(); // 方式1
store.dispatch({ // 方式2
type: ActionTypes.INCREMENT,
payload: 2,
});
3.自定义 useSelector,增加对 store 的提示
src/redux/useSelector.ts
import {
useSelector as useReduxSelector,
TypedUseSelectorHook,
} from 'react-redux';
import { ReduxState } from './reducer';
export const useSelector: TypedUseSelectorHook<ReduxState> = useReduxSelector;