前言
一个简单的react-redux使用例子:
大概的步骤如下:
- 创建页面(简单略过)
- 创建仓库
- 创建投票相关reduces
- 创建投票相关actions
- 创建仓库
- 向整个系统注入仓库
实现
基本的目录结构如下:
actios-type常量创建
// 动作类型常量
/** ------------------ 投票 ------------------ */
export const VOTE_SUP = 'VOTE_SUP' // 赞同
export const VOTE_OPP = 'VOTE_OPP' // 反对
对应文件:action-types
reduces的创建
/**
* 投票reducer
*/
import { cloneDeep } from 'lodash'
import * as TYPES from '../action-types'
// 初始值
const initialState = {
supNum: 0,
oppNum: 0,
}
// reducer函数
export default function voteReducer(state = initialState, action) {
state = cloneDeep(state)
switch (action.type) {
case TYPES.VOTE_SUP:
state.supNum += 1
break
case TYPES.VOTE_OPP:
state.oppNum += 1
break
default:
break
}
return state
}
- 需要一个初始值
- 每次执行reducer需要深拷贝一次state
- 根据action的类型执行相关修改state逻辑
- 对应文件:reducers/voteReducers
// 合并reducers
import { combineReducers } from "redux";
// import { counterReducer } from "./counter";
import voteReducer from "./voteReducer";
const rootReducer = combineReducers({
vote: voteReducer
});
// export type RootState = ReturnType<typeof rootReducer>;
export default rootReducer;
合并reducer
actions的创建
// 投票的actions
import * as TYPES from '../action-types';
const voteAction = {
support() {
return {
type: TYPES.VOTE_SUP
}
},
oppose() {
return {
type: TYPES.VOTE_OPP
}
}
}
export default voteAction;
- 看似麻烦,实际上为了组件更方便的注入dispatch函数
- 对应文件,action/voteAction
import voteAction from "./voteAction";
const actions = {
vote: voteAction
};
export default actions;
统一的出口
仓库的生成
有了reducer,就可以生成仓库。生成代码如下:
// 创建一个仓库并导出
import { createStore } from "redux";
import reducer from "./reducers";
const store = createStore(reducer);
export default store;
- 对应文件是store/index.ts
注入仓库
使用react-redux中提供的Provider组件进行store注入
import React from 'react'
import ReactDOM from 'react-dom/client'
import { Provider } from 'react-redux'
import Vote from './views/Vote'
import store from './store'
ReactDOM.createRoot(document.getElementById('root')!).render(
<Provider store={store}>
<Vote></Vote>
</Provider>
)
入口文件main.ts
组件使用仓库
经过上面几步件就可以使用仓库。
获取仓库的数据
import React from 'react'
import { connect } from'react-redux'
// 投票结果
function VoteContent(props) {
const {supNum, oppNum} = props
return (
<div>
<p>赞成:{supNum}</p>
<p>反对:{oppNum}</p>
</div>
)
}
export default connect((state) => ({
...state.vote
}))(VoteContent)
- 对应组件:VoteContent
- 使用的是react-redux提供的connect函数(高阶组件)
更改仓库的数据
import React from 'react'
import { connect } from 'react-redux'
import actions from '../store/actions'
// 投票的底部
function VoteFooter(props) {
const { support, oppose } = props
return (
<footer>
<button onClick={support}>赞成</button>
<button onClick={oppose}>反对</button>
</footer>
)
}
export default connect(null, actions.vote)(VoteFooter)
- 对应组件:VoteFooter
- 这个时候action的用处就体现出来了
传参
如果要传参,比如点击有可能是增加2或者3等等等,根据传参进行增加。