《React后台管理系统实战:九》Redux原理:优化【react-redux】概述及实战(二)

49 篇文章 6 订阅

一.问题

  1. redux 与 react 组件的代码耦合度太高
  2. 编码不够简洁

二. 解决方案:react-redux

中文档:https://cn.redux.js.org/docs/react-redux/

1. 理解

  1. 一个 react 插件库
  2. 专门用来简化 react 应用中使用 redux

2. React-Redux 将所有组件分成两大类

1) UI 组件

a. 只负责 UI 的呈现,不带有任何业务逻辑
b. 通过 props 接收数据(一般数据和函数)
c. 不使用任何 Redux 的 API
d. 一般保存在 components 文件夹下

2) 容器组件

a. 负责管理数据和业务逻辑,不负责 UI 的呈现
b. 使用 Redux 的 API
c. 一般保存在 containers 文件夹下

3. 相关 API

1) Provider

// 让所有组件都可以得到 state 数据
<Provider store={store}>
<App />
</Provider>

2) connect()

// 用于包装 UI 组件生成容器组件
connect(
mapStateToprops,
mapDispatchToProps
)(Counter)

3) mapStateToprops()

// 函数: 将 state 数据转换为 UI 组件的标签属性
function mapStateToProps (state) {
return {
count: state
}
}

4) mapDispatchToProps

// 函数: 将分发 action 的函数转换为 UI 组件的标签属性
function mapDispatchToProps(dispatch) {
return {
increment: (number) => dispatch(increment(number)),
decrement: (number) => dispatch(decrement(number)),
}
}
// 对象: 简洁语法, 可以直接指定包含多个 action 方法
const mapDispatchToProps = {
increment,
decrement
}

三. 使用 react-redux

1) 下载依赖包及创建文件夹

cnpm install --save react-redux
或
npm install --save react-redux

安装指定版本npm包
cnpm install  --save react-redux@^7.0.3

用命令新建两个文件夹src/components 和 containers

进入src, shift+右键 打开cmd(后面要用到)

mkdir components containers

2) redux/action-types.js不变

3) redux/actions.js不变

4) redux/reducers.js不变

5) redux/store.js不变

6) 改 index.js

import React from 'react' 
import ReactDOM from 'react-dom'
import App from './containers/App.js'
import store from './redux/store.js' //导入store
import {Provider} from 'react-redux' //【2】引入provider

//【3】改写App;   传store给App子组件
ReactDOM.render(( //【4】传入不止一个对象,记得加括号;把app的store移到provider里
    <Provider store={store}>
        <App/>
    </Provider>
),document.getElementById('root'))

/*【1】去除监听,react-redux里会自动添加
//给store绑定状态更新的监听
store.subscribe(() => { // store内部的状态数据发生改变时回调
    // 重新渲染App组件标签
    ReactDOM.render(<App store={store} />, document.getElementById('root'))
})
*/

7) 改src/App.jsx移到并改名components/Counter.jsx

此时此组件用途为UI组件,作用如下:
  1. 主要做显示与与用户交互
  2. 代码中没有任何redux相关的代码
import React,{Component} from 'react'
import PropTypes from 'prop-types' //引入propTypes
//import {increment,decrement} from './redux/actions' //【0】没用了,删除


/*
UI组件:
  主要做显示与与用户交互
  代码中没有任何redux相关的代码
 */
export default class App extends Component{
    
    //【1】接收相关参数
    static propTypes={
      count:PropTypes.number.isRequired,
      increment:PropTypes.func.isRequired, 
      decrement:PropTypes.func.isRequired, 
    }

    constructor(props) {
      super(props)
      this.numberRef = React.createRef() //创建一个ref
    }


    //自加 increment
    increment = () => {
        const number = this.numberRef.current.value * 1 //引用ref处的当前值
        // this.setState(state => ({count: state.count + number}))
        this.props.increment(number)  //【2】改为用接收到的函数处理数据 下同
    }

    //自减
    decrement = () => {
        const number = this.numberRef.current.value * 1
        this.props.decrement(number) //【3】用接收到的函数处理数据
      }
    
      //如果当前是奇数就进行自加
      incrementIfOdd = () => {
        const number = this.numberRef.current.value * 1
        if (this.props.count % 2 === 1) {
          this.props.increment(number) //【4】用接收到的函数处理数据
        }
    
      }

      //异步自加,此处用隔一秒加模拟异步
      incrementAsync = () => {
        const number = this.numberRef.current.value * 1
        setTimeout(() => {
          this.props.increment(number) //【5】用接收到的函数处理数据
        }, 1000)
      }

    render(){
        //【6】得到count的数据,来自接收到的count
        const count = this.props.count
        return(
            <div>
                <p>click {count} times</p>
                <select ref={this.numberRef}> {/**使用ref */}
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select> &nbsp;&nbsp;
                <button onClick={this.increment}>+</button>&nbsp;&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;&nbsp;
                <button onClick={this.incrementIfOdd}>increment if odd</button>&nbsp;&nbsp;
                <button onClick={this.incrementAsync}>increment async</button>
            </div>
        )
    }
}

8) 在目录下创建 containters/App.jsx

1.此为容器组件作用是: 通过connect包装UI组件产生组件
  • connect(): 高阶函数
  • connect()返回的函数是一个高阶组件: 接收一个UI组件, 生成一个容器组件
2.容器组件的责任: 向UI组件传入特定的属性
  • 用来将redux管理的state数据映射成UI组件的一般属性的函数
import React, {Component} from 'react'
import {connect} from 'react-redux'

import Counter from '../components/Counter'
import {increment, decrement} from '../redux/actions'

// 指定向Counter传入哪些一般属性(属性值的来源就是store中的state)
const mapStateToProps = (state) => ({count: state})
// 指定向Counter传入哪些函数属性
/*如果是函数, 会自动调用得到对象, 将对象中的方法作为函数属性传入UI组件*/
/*const mapDispatchToProps = (dispatch) => ({
  increment: (number) => dispatch(increment(number)),
  decrement: (number) => dispatch(decrement(number)),
})*/
/*如果是对象, 将对象中的方法包装成一个新函数, 并传入UI组件 */
//因为会自动回调,所以可以直接传入对象,react-redux会自动回调dispatch
const mapDispatchToProps = {increment, decrement}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter)

containers/app.jsx最终简写法

import {connect} from 'react-redux'
import Counter from '../components/counter.js'
import {increment,decrement} from '../redux/actions.js'

export default connect(
	state=>({count:state}),
	{increment,decrement},
)(Counter)

注:以上只是简写写法,app.jsx的基础写法其实是这样app_base.jsx:

import React, {Component} from 'react'
import {connect} from 'react-redux' //【0】引入连接模块
import Counter from '../components/Counter' //【1】引入components下的counter.jsx 注意路径
import {increment, decrement} from '../redux/actions' //【2】引入redux下的动作

/*
容器组件: 通过connect包装UI组件产生组件
connect(): 高阶函数
connect()返回的函数是一个高阶组件: 接收一个UI组件, 生成一个容器组件
容器组件的责任: 向UI组件传入特定的属性
*/

/*
用来将redux管理的state数据映射成UI组件的一般属性的函数
*/
function mapStateToProps(state) {
    return {
      count: state
    }
  }
  
  /*
  用来将包含diaptch代码的函数映射成UI组件的函数属性的函数
   */
  function mapDispatchToProps (dispatch) {
    return {
      increment: (number) => dispatch(increment(number)),
      decrement: (number) => dispatch(decrement(number)),
    }
  }
  
  export default connect(
    mapStateToProps,  // 指定一般属性
    mapDispatchToProps // 指定函数属性
  )(Counter)

9)问题

  1. redux 默认是不能进行异步处理的,
  2. 应用中又需要在 redux 中执行异步任务(ajax, 定时器)

报错及解决:

Invalid hook call. Hooks can only be called inside of the body of a function component......

【解决】:这个问题其实是版本间的依赖对不上,删除node_modules所有安装包,重新cnpm install安装依赖。问题解决。

package.json参考

{
  "name": "admin-client_final",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@antv/data-set": "^0.10.2",
    "antd": "^3.17.0",
    "axios": "^0.18.0",
    "babel-plugin-import": "^1.11.0",
    "bizcharts": "^3.5.2",
    "customize-cra": "^0.2.12",
    "draft-js": "0.10.5",
    "draftjs-to-html": "^0.8.4",
    "echarts": "^4.2.1",
    "echarts-for-react": "^2.0.15-beta.0",
    "html-to-draftjs": "1.4.0",
    "jsonp": "^0.2.1",
    "less": "^3.9.0",
    "less-loader": "^5.0.0",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-app-rewired": "^2.1.3",
    "react-dom": "^16.8.6",
    "react-draft-wysiwyg": "^1.13.2",
    "react-redux": "^7.0.3",
    "react-router-dom": "^5.0.0",
    "react-scripts": "3.0.1",
    "redux": "^4.0.1",
    "redux-devtools-extension": "^2.13.8",
    "redux-thunk": "^2.3.0",
    "store": "^2.0.12"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:5000"
}

效果同一

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值