• React16、18 使用 Redux


    Redux 核心

    Redux 介绍

    Redux 是javaScript 状态容器,提供可预测化的状态管理

    Redux 工作流程

    在这里插入图片描述

    Actions:对象,描述对状态进行怎样的操作

    Reducer:函数,操作状态并返回新的状态

    Store:存储状态的容器,JavaScript对象

    View:视图,HTML页面

    React 16 使用 Redux

    安装

    npm install --save redux
    
    • 1

    创建 store 仓库

    src 目录下创建一个 store 文件夹,然后在文件夹下创建一个 index.js 文件

    import { legacy_createStore as createStore } from "redux";
    import reducer from "./reducer";
    
    const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) // 创建数据存储仓库
    
    export default store
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    store 文件夹下创建一个 reducer.js 文件

    const defaultstate = {
        list: [1,2,3,4,5,6],
        inpuValue: ''
    }
    
    export default (state = defaultstate) => {
        return state;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    在页面中使用

    src 目录下创建 TodoList.js 页面

    constructor 引入

    this.state=store.getState();
    
    • 1

    使用

    this.state.list
    
    • 1

    通过 dispatch 修改里面的值

    store.dispatch({
       type: 'changeList',
       value: newList
    })
    
    • 1
    • 2
    • 3
    • 4

    reducer.js 添加对应的方法

    const defaultstate = {
        list: [1,2,3,4,5,6],
        inpuValue: ''
    }
    
    export default (state = defaultstate, action) => {
        switch(action.type) {
            case "changeList":
                return {
                    ...state,
                    list: action.value
                }
            default:
                return state;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    constructor 添加 订阅Redux的状态

    this.storeChange = this.storeChange.bind(this) 
    store.subscribe(this.storeChange) 
    
    • 1
    • 2

    编写storeChange方法

    storeChange(){
        this.setState(store.getState())
    }
    
    • 1
    • 2
    • 3

    完整代码

    import React, { Component } from 'react';
    import store from './store'
    
    class TodoList extends Component {
    	 constructor(props){
         super(props)
         this.state=store.getState();
         this.storeChange = this.storeChange.bind(this)
    		 store.subscribe(this.storeChange) 
    	 }
    	 
    	 handleChange(){
    			this.setState({
            inputValue:this.inputRef.value
        	})
       }
       
       handleAdd() {
       		let newList = this.state.list
          newList.push(this.inputRef.value)
          store.dispatch({
              type: 'changeList',
              value: newList
          })
          this.setState({
            inputValue: ''
        	})
       }
       
       handledel(index) {
       		const list = this.state.list
          list.splice(index, 1)
          store.dispatch({
              type: 'changeList',
              value: list
          })
       }
       
       storeChange(){
         this.setState(store.getState())
       }
    	 
       render() { 
            return ( 
                
    {this.inputRef=inputRef}} value={this.state.inputValue} onChange={handleChange.bind(this)} />
    {this.state.list.map((item, index) => { return (

    {item} handledel(index).bind(this)}> 删除

    ) })}
    ); } } export default TodoList;
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    React 18 使用 Redux

    安装、创建仓库都与16一样

    使用

    正常引入,用一个变量接收

    import store from './store'
    
    • 1
    const state = store.getState()
    
    • 1

    使用的时候 直接state.xxx 就能使用

        const items = state.list.map((item, index) => {
            return (

    {item} handledel(index)}> 删除

    ) })
    • 1
    • 2
    • 3

    修改

    一样通过 dispatch

    store.dispatch({
        type: 'changeList',
        value: list
    })
    
    • 1
    • 2
    • 3
    • 4

    为了能让页面实时更新,必须手动更新

    使用 react自带的 useEffect 方法,通过 subscribe 监测store更新的函数

    useEffect(() => {
            // store.subscribe()是redux提供的,监测store更新的函数
            store.subscribe(() => {
                // 当store数据更新后执行 setUpdate() ,组件重新加载,实现界面store数据更新
                setUpdate({})
            })
        })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    const [update,setUpdate] = useState({})
    
    • 1

    完整代码

    import React, { useRef, useState, startTransition, useEffect } from 'react';
    import store from './store'
    
    const TotoList = () => {
        const inputRef = useRef()
    
        const state = store.getState()
    
        const [update,setUpdate] = useState({})
    
        const [value, setValue] = useState('')
    
        const items = state.list.map((item, index) => {
            return (

    {item} handledel(index)}> 删除

    ) }) const handleChange = () => { startTransition(()=> { setValue(inputRef.current.value) }) } const handleAdd = () => { let newList = state.list newList.push(inputRef.current.value) store.dispatch({ type: 'changeList', value: newList }) setValue('') } const handledel = (key) => { const list = state.list list.splice(key, 1) store.dispatch({ type: 'changeList', value: list }) } useEffect(() => { // store.subscribe()是redux提供的,监测store更新的函数 store.subscribe(() => { // 当store数据更新后执行 setUpdate() ,组件重新加载,实现界面store数据更新 setUpdate({}) }) }) return (
    {items}
    ) } export default TotoList;
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
  • 相关阅读:
    【24种设计模式】责任链模式(Chain of Responsibility Pattern)
    考虑关系的图卷积神经网络R-GCN的一些理解以及DGL官方代码的一些讲解
    [计算机网网络] 计算机网络挂科小知识
    [userfaultfd] 2019-BalsnCTF_KrazyNote
    454. 四数相加 II
    ASP.NET Core Web项目连接MySQL数据库
    【JAVA知识梳理】异常机制
    阿里云搭建samba
    基于jsp+mysql+ssm进销存管理系统-计算机毕业设计
    大型客户关系管理系统源码CRM
  • 原文地址:https://blog.csdn.net/weixin_44872023/article/details/132756608