redux
redux是什么
- redux是一个专门用于做状态管理的JS库(不是react 插件库)。
 - 可以用在react,angular,vue等项目中,但是基本与react配合使用。
 - 作用:集中式管理react应用中多个组件共享的状态。
redux工作流流程
怎么用:view 调用 store 的 dispatch 接收 action 传入 store,reducer 进行 state 操作,view 通过 store 提供的 getState 获取最新的数据
缺点: state必须由父组件传过来,子组件相关数据更新,父组件会强渲
 
案例:
安装:
yarn add redux react-redux redux-thunk
redux    构建redux架构
react-redux react自己的插件,简化react应用中使用redux(用户数据划分 数据—> 用户|商品|管理等)
redux-thunk    异步数据交互[处理前后端交互]
打造redux中的store
项目目录/src/创建store/index.ts
// 文件名或者叫models。 用于打造redux构成之一:storeimport { createStore, applyMiddleware } from 'redux'import rootReducer from '../reducers'import thunk from 'redux-thunk'// const store=createStore(rootReducer,中件件执行函数)const store = createStore(rootReducer, applyMiddleware(thunk))export default store
- createstore()
- 作用:创建包含指定 
reducer的store对象 
 - 作用:创建包含指定 
 - applyMiddleware()
- 作用:应用上基于redux的中间件(插件库)
 
 
打造rootReducer
项目目录/src/创建reducers/index.ts
// 打造rootReducerimport{combineReducers} from 'redux'import homeReducer from './homeReducer'// 作用:合并多个reducer函数// rootReducer 统一一处管理项目中的所有reducerconst rootReducer=combineReducers({// 数据名:reducerhome:homeReducer})export default rootReducer
- combineReducers()
- 作用:合并多个reducer函数
 
 
项目目录/src/reducers/homeReducer.ts
// homeReducer 就是home相关的所有数据都在这里// 作用:初始化状态,加工状态// todo、1初始话数据const initState = {hotList: [],classicList:[]}// reducer本质是一个函数,接受State,action,返回加工后的状态// reducer被第一调用时,是store自动触发的,传递的State是undefinedconst homeReducer = (state = initState, action: {type: string,payload: {[key: string]: any}}) => {/*state就是状态,也就是数据action是一个对象,是由actionCreators发送过来的动作reducer 一定有返回值 返回一个新的state,因为state不可更改,所以返回新状态一定是state的拷贝*/switch (action.type) {case 'GET_HOT_LIST':// 获取hot的数据return { ...state, hotList: action.payload.data.content }case 'GET_CLASSIC':return{...state,classicList:action.payload.data.content}default:return { ...state }}}export default homeReducer
链接通信
项目目录index.tsx
import。。。// 使用跨组件通信的方法将store中的数据通信给所有的组件import { Provider } from 'react-redux'import store from './store'ReactDOM.render(<Provider store={store}><App /></Provider>,document.getElementById('root')。。。
- Provider让所有组件都可以得到state数据
 
组件中使用
import React,{useEffect} from 'react'// 组件需要通过调用一个叫做connect的函数,他的返回值是一个的高阶组件来获取store中的数据// 用于包装 UI 组件生成容器组件import { connect } from 'react-redux'// 激活方法import homeActions from '../../actions/homeActions'import {bindActionCreators} from 'redux'interface P{hotList:{[key:string]:any}[]getHotList:(params:{cid:number})=>any}function Hot(props:P) {console.log(props)const {hotList, getHotList}=props;useEffect(()=>{getHotList({cid:17})},[])return (<>Hot <hr /><ul>{hotList && hotList.map(item=><li key={item.id}><p>{item.title}</p></li>)}</ul></>)}export default connect((state:{home:{ }}) => {console.log('state', state) // state是整个应用的所以数据,里面的home指的是划分出来的home数据return state.home}, (dispatch) => {return bindActionCreators(homeActions,dispatch)})(Hot)/*connect 有两个参数,第一个参数用于获取store中的state的将外部的数据(即state对象)转换为UI组件的标签属性第二个参数用于获取redux中的actionCreators中创建动作的方法将分发action的函数转换为UI组件的标签属性*/
- connect
- 用于包装UI组件生成容器组件
 
 
Line34打印结果
react-redux的connect用法详解
- bindActionCreators()
- 作用是将单个或多个ActionCreator转化为dispatch(action)的函数集合形式。
 
 
开发者不用再手动dispatch(actionCreator(type)),而是可以直接调用方法.
可以实现简化书写,减轻开发的负担。
发送请求
项目目录/src/service/index.ts
// 提前书写数据请求export const fetchHotListReq = (params: { cid: number }) => {return new Promise((resolve, reject) => {fetch(`http://59.110.226.77:3000/api/list/hot?cid=${params.cid}`).then(data => data.json()).then(res => {resolve(res)}).catch(error => reject(error))})}export const fetchClassicReq =(params:{cid:number})=>{return new Promise((resolve,reject)=>{fetch(`http://59.110.226.77:3000/api/list/sell?cid=${params.cid}`).then(data=>data.json()).then(res=>{resolve(res)}).catch(error=>reject(error))})}
创建动作对象Actioncreates
项目目录/src/actions/homeActions.ts
// 书写home的所有action createimport { Dispatch } from 'redux' // 类型声明import * as service from '../service'const homeActions = {getHotList(params: { cid: number }) {// 发送异步数据请求return async (dispatch: Dispatch) => {// result就是数据请求结果const result = await service.fetchHotListReq(params)// 将result发送给reducerdispatch({type: 'GET_HOT_LIST', //动作类型,用产量表示,我们将方法名大写payload: result})}},getClassic(params: { cid: number }) {return async (dispatch: Dispatch) => {const result = await service.fetchClassicReq(params)dispatch({type: 'GET_CLASSIC',payload: result})}}}export default homeActions

