react 状态管理
redux
一、什么时候用到redux
1、用户的使用方式复杂1
2、不同身份的用户有不同的使用方式(比如普通用户和管理员)
3.多个用户之间协作
4、与服务器大量交互
5、 view要从多个来源获取数据
二、 单一数据源
1、整个应用的state被存储在一个object tree中,并且这个object tree 只存在于唯一store中
2、state只读
唯一改变state的方法就是action,action是一个用于描述已发生事件的普通对象
3、使用纯函数来执行修改
为了描述action如何改变state tree ,你需要编写reducers
store有以下职责
维持应用的state
提供getState()方法获取state
提供dispatch(action)方法更新state
通过subscribe(listener)注册监听器
通过subscribe(listener)返回的函数注销监听器
import { createStore } from 'redux'
const initState = {
count: 0
}function reducer(state = initState,action){
switch(action.type){
case 'cadd':
return {
...state,
count: state.count + action.count
}
case 'decre':
return {
...state,
count: state.count - action.count
}
default:
return {
...state
}
}
}const store = createStore(reducer);
expoort default store;
import React,{Component} from 'react';
import Storefrom 'store';
class Count extends Component {
add(){
store.dispatch({type:'incre', count:5})
}
componentDidMount(){
this.clear = store.subscribe(() => {//store.subscribe 触发监听state的更新 // 返回一个函数 清除监听
this.setState({})
})
}
componentDidUpdate(){
this.clear() // 清除
}
render(){
let state = store.getState;
return ({state.count}
)
}
}
简单自己实现一个reducer
export function createStore(reducer){
let state;
let eventListeners = [] // 事件池
function getState(){
return state;
}
function dispatch(action){
state = reducer(state,action);
eventListeners.forEach(item => {
item && item();
})
}
function subscribe(fn){
eventListeners.psush(fn)
return (fn) => {
eventListeners.filter((item) => item === fn)
}
}
dispatch({}) // 初始化state的数据,通过执行reducer
return {
getState,
dispatch,
subscribe,
}
}
自己实现react-reducer
// 自己实现react-redux
import React, { Component } from 'react'
export const MyContext = React.createContext();
export class Provider extends Component{
render(){
let {children, sotre } = this.props;
return
{children}
}
} export function connect(mapStateToProps, mapDispatchToProps){
return function(comp){
return class Temp extends Component{
constructor(props, context){ // 此处的context 是MyContext传进来的
super(props,context);
this.state = mapStateToProps(context.getState())
this.dispatch = mapDispatchToProps(context.dispatch);
}
static contextType = MyContext;
// 静态属性此时本地就有this.context
componentDidMount(){
this.context.subscribe(() => {
this.setState( // 更新,重新渲染
mapStateToProps(this.context.getState())
)
})
}
render(){
return
}
}
}
}
combineReducers
function reducer1(){
//...
} function reducer2 (){
//...
} export default store = createStore(combineReducers({
reducer1,
reducer2
}))
// 实现原理
export function combineReducers(obj) {// 返回值是一个reducer方法
return function(state = {},action){
Object.keys(obj).forEach((key) => {
state[key] = obj[key](state[key], action)
})
return state
}
}
mobox
【react 状态管理】灵活
性能 哪更新哪加载
推荐阅读
- 基于微信小程序带后端ssm接口小区物业管理平台设计
- 2020-04-07vue中Axios的封装和API接口的管理
- 全过程工程咨询——时间管理(12)
- 《卓有成效的管理者》第二十二堂课(创造英雄)
- 游乐园系统,助力游乐园管理
- #山言良语#用管理思维百天减肥18斤
- 最有效的时间管理工具(赢效率手册和总结笔记)
- 停下“忙乱”的状态
- Java基础-高级特性-枚举实现状态机
- react|react 安装