react系列---【redux进阶】

# 1.redux
### 1.action creators
作用:统一管理所有的Actions
```js
//action creator
export let actions = {
changeName: (name) => {
return
},
changeAge: (age) => ({ type: TYPES.CHANGE_AGE, age: age }),
changeSex: sex => ({ type: TYPES.CHANGE_SEX, sex: sex })
}
```
### 2.action types
作用:统一管理所有的types
```jsx
//action types
const TYPES = {
CHANGE_NAME: "CHANGE_NAME",
CHANGE_AGE: "CHANGE_AGE",
CHANGE_SEX: "CHANGE_S"
}
```
### 3.reducer拆分
作用:reducer进行拆分,这样便于后期扩展和维护
Eg:order.js模块
```js
//初始值
const initState={
list:[]
}
//action types
const TYPES={
CHANGE_LIST:"CHANGE_ORDER_LIST"
}
//reducer
const reducer=(state=initState,action)=>{
switch(action.type){
//{type:"changeList",arr:[{},
case TYPES.CHANGE_LIST:
return {
...state,
list:action.arr
}
default:
return state;
}
}
// action creator
export let actions={
changeList:arr=>{
return
}
}
export default reducer
```
Shop.js
```js
//初始值
const initState={
list:[]
}
//action types
const TYPES={
CHANGE_LIST:"CHANGE_SHOP_LIST"
}
//reducer
const reducer=(state=initState,action)=>{
switch(action.type){
//{type:"changeList",arr:[{},
case TYPES.CHANGE_LIST:
return {
...state,
list:action.arr
}
default:
return state;
}
}
// action creator
export let actions={
changeList:arr=>{
return
}
}
export default reducer
```
通过combineReducers 合并reducer . [src/store/index.js]
```js
import { createStore,combineReducers } from "redux"
//引入模块
import order from "./modules/order"
import shop from "./modules/shop"
import user from "./modules/user"
// 合并reducer
let rootReducer=combineReducers({
// 模块名:模块对应的reducer
order:order,
shop,
user
})
//创建仓库
let store = createStore(rootReducer)
//导出仓库
export default store
```
### 4.redux devTools调试工具
# 2.react-redux
### 容器型组件VS展示型组件
# 3.redux高阶
### 1.bindActionCreators
组件想要所有的actions上的方法进行dispatch
```js
import { actions } from "../store";
import { bindActionCreators } from "redux";
```
```js
const mapDispatchToProos = (dispatch) => {
//通过bindActionCreators 将actions上的方法统统导入到fn
return {
fn: bindActionCreators(actions, dispatch),
// changeName:(name)=>dispatch(actions.changeName(name ))
};
};
```
### 2.selectors
### 3.reselect
### 4.redux middleware
#

posted on 2021-06-09 22:38  码农小小海  阅读(40)  评论(0编辑  收藏  举报

导航