React从入门到“放弃”系列之--Redux(上)

为什么出现Redux?
阮一峰大佬的日志里提到,React没有涉及到代码结构和组件之间的通信,没法儿写大型复杂应用。为了解决这个问题,2014年Facebook提出Flux架构,2015年出现Redux,将Flux和函数式编程结合在一起。

React状态管理的发展:Flux ——> Redux ——> Mobx

大佬说:Redux 的设计思想很简单:
(1)Web 应用是一个状态机,视图与状态是一一对应的。
(2)所有的状态,保存在一个对象里面。

安装

# NPM
npm install redux
# Yarn
yarn add redux

核心API

  • Action

  • Reducer

  • Store

  • state是数据集合,其它组件可以通过订阅store中的状态更新视图;

  • state变化会导致view变化,但是用户只能接触到view,所以通过action改变state;

  • action发出命令将state给reducer加工后,返回新的state;

  • store提供getState()获取state;

  • store提供dispatch(action)更新state;

  • 通过 subscribe(listener) 注册监听器;

  • 通过 subscribe(listener) 返回的函数注销监听器;
    在这里插入图片描述
    在这里插入图片描述
    举个栗子!

import { createStore } from 'redux'

const reducer = (state = {count: 0}, action) => {
  switch (action.type){
    case 'INCREASE': return {count: state.count + 1};
    case 'DECREASE': return {count: state.count - 1};
    default: return state;
  }
}

const actions = {
  increase: () => ({type: 'INCREASE'}),
  decrease: () => ({type: 'DECREASE'})
}

const store = createStore(reducer);

store.subscribe(() =>
  console.log(store.getState())
);

store.dispatch(actions.increase()) // {count: 1}
store.dispatch(actions.increase()) // {count: 2}
store.dispatch(actions.increase()) // {count: 3}

在react 组件上使用store.dispatch不方便,用react-redux试一下 ↓
(react-redux:Redux 官方提供的 React 绑定库)

class Todos extends Component {
    render(){
        return(
            <div onCLick={()=>store.dispatch(actions.delTodo()) }>test</div>
        )
    }
}

react-redux中的connect方法将store上的getState 和 dispatch 包装成组件的props

// index.js
import React, { Component } from 'react';
import store from '../store';
import actions from '../store/actions/list';
import {connect} from 'react-redux';

class Todos extends Component {
    render(){
        return(
            <div onCLick={()=>this.props.del_todo() }>test</div>
        )
    }
}

export default connect(state=>state,actions)(Todos);

(下篇react-redux)
-----------------------------------------学(tu)到(tou)了-----------------------------------------
我个人开了一个微信公众号,每天会分享一些JavaScript技术相关的基础干货!
欢迎用微信搜索【易碎品啊今天吃什么研究所】或者【扫描下方二维码】关注和我一起在疫情中逆战JavaScript365!❤️
在这里插入图片描述
参考文章:
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
https://juejin.im/post/5af00705f265da0ba60fb844
https://www.jianshu.com/p/faa98d8bd3fa


版权声明:本文为qq_23688355原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。