Redux中subscribe的作用及说明
作者:*唔西迪西*
由于redux使用这方面有很多的不解,不是很熟练,所以我查找资料,进行一个总结,希望可以巩固知识,并且能帮助到需要的人,所以我会写的比较清晰简单明了点,若有不对之处,请大家纠正
Redux中subscribe的作用
redux的使用步骤过程
首先安装redux
安装命令:
npm install redux
redux使用过程(原理)
- 使用函数createStore创建store数据点
- 创建Reducer。它要改变的组件,它获取state和action,
- 生成新的state 用subscribe监听每次修改情况
- 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())
})Redux的store.subscribe()监听
import createStore from 'Redux'
const { store } = createStore(reducer)
store.subscribe(放上view的更新函数)//对于React 则是render和setState此后 更新函数的每一次变化都会触发view的重新自动渲染
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
