IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> React学习笔记之redux与react-redux -> 正文阅读

[JavaScript知识库]React学习笔记之redux与react-redux

前言

React学习笔记系列仅为个人学习React后的代码总结,用于巩固与记录些重点知识,详细视频资源请参考bilibili:尚硅谷2021版React技术全家桶全套完整版(零基础入门到精通/男神天禹老师亲授)

安装

// 安装redux
 npm install redux  
 // 安装支持异步Action的中间件redux-thunk
 npm install redux-thunk
 // 安装react-redux
 npm install redux-thunk

redux使用

redux是一个专门用于做状态管理的JS库(不是react插件库),它可以用在react, angular, vue等项目中, 但基本与react配合使用,作用是集中式管理react应用中多个组件共享的状态。

原理

在这里插入图片描述
在src下新建redux文件夹,在redux下新建constant.js、count_action.js、count_reducer.js以及store.js,详细代码如下:

定义静态变量constant.js

export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

实现ActionCreators(count_action.js)

import {INCREMENT,DECREMENT} from './constant'

// 同步Action
export const Increment = data => ({type:INCREMENT,data})
export const Decrement = data => ({type:DECREMENT,data})
// 异步Action
export const IncrementAsync = (data,time) => {
    return (dispatch) => {
        setTimeout(()=>{
          dispatch(Increment(data))
        },time)
    }
}

实现Store(store.js)

import {createStore,applyMiddleware} from 'redux'
import countReducer from './count_reducer'
import thunk from 'redux-thunk'
// 用于支持异步Action需要applyMiddleware和thunk
export default createStore(countReducer,applyMiddleware(thunk))

实现Reducers(count_reducer.js)

 import {INCREMENT,DECREMENT} from './constant'

//  用于初始化
 const initState = 0
 export default function countReducer(preState = initState,action){
    const {type,data} = action
    switch (type) {
        case INCREMENT:           
          return preState + data;
        case DECREMENT:           
          return preState - data;
        default:
          return preState;
    }
 }

实现Count组件

在src下新建component,在component下新建Count,然后在Count下新建index.js

 import React, { Component } from 'react'
import store from '../../redux/store'
import {
    Increment,
    Decrement,
    IncrementAsync
} from '../../redux/count_action'

export default class Count extends Component {

    increment = () =>{
      const {value} = this.selectNumber
      store.dispatch(Increment(value*1))
    }
    decrement = () =>{
      const {value} = this.selectNumber
      store.dispatch(Decrement(value*1))

    }
    incrementIFOdd = () =>{
      const {value} = this.selectNumber
      if (store.getState() % 2 !== 0) {
        store.dispatch(Increment(value*1))
      }
    }
    incrementAsync = () =>{
      const {value} = this.selectNumber
      store.dispatch(IncrementAsync(value*1,500))
    }
    render() {
        return (
            <div>
              <h1>当前求和为:{store.getState()}</h1>
              <select ref={c => this.selectNumber = c}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
              </select>&nbsp;
              <button onClick = {this.increment}>+</button>&nbsp;
              <button onClick = {this.decrement}>-</button>&nbsp;
              <button onClick = {this.incrementIFOdd}>当前求和为奇数再加</button>&nbsp;
              <button onClick = {this.incrementAsync}>异步加</button>&nbsp;
            </div>
        )
    }
}

App.js

import React, { Component } from 'react'
import Count from './components/Count'
import store from './redux/store'

export default class App extends Component {
    render() {
        return (
            <div>
              <Count/>
            </div>
        )
    }
}

程序入口index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'

ReactDOM.render(<App/>,document.getElementById('root'))

//用于当redux内的state更新时重新渲染界面的
store.subscribe(()=>{
    ReactDOM.render(<App/>,document.getElementById('root'))
})

react-redux使用

原理

在这里插入图片描述redux的代码无需改变,使用react-redux后无需再使用store.subscribe去监听redux的状态了,其中使用的connect将自动去监听,且无需为每个容器组件都提供store,可以使用react-redux提供的Provider去批量的给所有的容器组件传递store。

程序入口index.js

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(
  <Provider store = {store}>
    <App/>
  </Provider>,
  document.getElementById('root')
)

// store.subscribe(()=>{
//     ReactDOM.render(<App/>,document.getElementById('root'))
// })

容器组件(container->Count->index.js)

在src下新建container->Count->index.js

import CountUI from '../../components/Count'
import {connect} from 'react-redux'
import {
    Increment,
    Decrement,
    IncrementAsync
} from '../../redux/count_action'

// mapStateToProps函数返回对象中的key就是作为传递给UI组件props的key,value就作为传递UI组件props的value----状态
// mapStateToProps函数是由redux帮我们调的并且已经执行getState(),除此之外还将其返回值传给mapStateToProps (state)
function mapStateToProps (state) {
    return {count: state}
}
// mapDispatchToProps传递操作状态的函数
function mapDispatchToProps (dispatch) {
    return {
      increment: (number) => {
        dispatch(Increment(number))
      },
      decrement: (number) => {
        dispatch(Decrement(number))
      },
      incrementAsync: (number,time) => {
        dispatch(IncrementAsync(number,time))
      }
    }
}

// 容器组件与UI组件建立联系并暴露
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)

UI组件(component->Count->index.js)

import React, { Component } from 'react'

export default class Count extends Component {

    increment = () =>{
      const {value} = this.selectNumber
      this.props.increment(value*1)
    }
    decrement = () =>{
      const {value} = this.selectNumber
      this.props.decrement(value*1)

    }
    incrementIFOdd = () =>{
      const {value} = this.selectNumber
      if (this.props.count % 2 !== 0) {
        this.props.increment(value*1)
      }
    }
    incrementAsync = () =>{
      const {value} = this.selectNumber
      this.props.incrementAsync(value*1,500)
    }
    render() {
        return (
            <div>
              <h1>当前求和为:{this.props.count} </h1>
              <select ref={c => this.selectNumber = c}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
              </select>&nbsp;
              <button onClick = {this.increment}>+</button>&nbsp;
              <button onClick = {this.decrement}>-</button>&nbsp;
              <button onClick = {this.incrementIFOdd}>当前求和为奇数再加</button>&nbsp;
              <button onClick = {this.incrementAsync}>异步加</button>&nbsp;
            </div>
        )
    }
}

App.js

import React, { Component } from 'react'
import Count from './containers/Count'

export default class App extends Component {
    render() {
        return (
            <div>
              <Count/>
            </div>
        )
    }
}

mapDispatchToProps简写

原因是因为Increment等是一个含参数的函数,且react-redux将会实现自动分发(dispatch),总结mapDispatchToProps即可是一个函数,也可是个对象。

{
increment:Increment,
decrement:Decrement,
incrementAsync:IncrementAsync,
}

合并容器组件与UI组件

将component->Count->index.js整合到container->Count->index.js,原因是如果将组件分为容器与UI那么当组件个数多的时候将成倍增长导致项目文件过多。

合并后的container->Count->index.js

import {connect} from 'react-redux'
import {
    Increment,
    Decrement,
    IncrementAsync
} from '../../redux/count_action'
import React, { Component } from 'react'

class Count extends Component {

  increment = () =>{
    const {value} = this.selectNumber
    this.props.increment(value*1)
  }
  decrement = () =>{
    const {value} = this.selectNumber
    this.props.decrement(value*1)

  }
  incrementIFOdd = () =>{
    const {value} = this.selectNumber
    if (this.props.count % 2 !== 0) {
      this.props.increment(value*1)
    }
  }
  incrementAsync = () =>{
    const {value} = this.selectNumber
    this.props.incrementAsync(value*1,500)
  }
  render() {
      return (
          <div>
            <h1>当前求和为:{this.props.count} </h1>
            <select ref={c => this.selectNumber = c}>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
            </select>&nbsp;
            <button onClick = {this.increment}>+</button>&nbsp;
            <button onClick = {this.decrement}>-</button>&nbsp;
            <button onClick = {this.incrementIFOdd}>当前求和为奇数再加</button>&nbsp;
            <button onClick = {this.incrementAsync}>异步加</button>&nbsp;
          </div>
      )
  }
}


// mapStateToProps函数返回对象中的key就是作为传递给UI组件props的key,value就作为传递UI组件props的value----状态
// mapStateToProps函数是由redux帮我们调的并且已经执行getState(),除此之外还将其返回值传给mapStateToProps (state)
function mapStateToProps (state) {
    return {count: state}
}

function mapDispatchToProps (dispatch) {
    return {
      increment: (number) => {
        dispatch(Increment(number))
      },
      decrement: (number) => {
        dispatch(Decrement(number))
      },
      incrementAsync: (number,time) => {
        dispatch(IncrementAsync(number,time))
      }
    }
}

// 容器组件与UI组件建立联系并暴露
export default connect(mapStateToProps,mapDispatchToProps)(Count)
  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-07-13 17:22:27  更:2021-07-13 17:22:32 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/4 23:43:19-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码