Redux中subscribe的作用

由于redux使用这方面有很多的不解,不是很熟练,所以我查找资料,进行一个总结,希望可以巩固知识,并且能帮助到需要的人,所以我会写的比较清晰简单明了点,若有不对之处,请大家纠正

1.redux的使用步骤过程

1.1首先安装redux

安装命令:npm install redux

1.2redux使用过程(原理)

  1. 使用函数createStore创建store数据点
  2. 创建Reducer。它要改变的组件,它获取state和action,
  3. 生成新的state 用subscribe监听每次修改情况
  4. dispatch 一个派发方法,将action 派发给reducer 更改state

代码如下:
创建一个组件

import React, { Component } from 'react'
import store from "./store";
import axios from 'axios';
export class DD extends Component {

    constructor(props){
        super(props);
        this.state = store.getState();
        //subscribe当store中数据发生变化就会更新数据
        store.subscribe(()=>{
            this.setState(store.getState())
        })

    }
    render() {
        return (
            <div>
                hengheng,我很生气
            </div>
        )
    }
}

export default DD

主要用subscribe监听store中每次修改情况

   store.subscribe(()=>{
            this.setState(store.getState())
        })

猜你喜欢

转载自blog.csdn.net/weixin_46041654/article/details/103894759