废话很少说,先上一张图javascript
首先记住redux设计思想java
Web应用是一个转态机,视图与转态是一一对应的react
全部的转态,保存在一个对象里redux
1.store函数
存储数据的容器,整个应用只有一个state,Redux提供createStore这个函数生成Store,Redux store保存了根reducer返回的完整state树ui
1 const { createStore } = require('redux') 2 //建立store的时候就要把reducer放进去,reducer改state,state写在reducer里 3 //store提供三个方法 4 /* 5 store.getState() 获取state 6 store.dispatch(action) 更新state 7 store.subscribe(listener) 注册监听器 8 */ 9 const store = createStore(reducer) 10 console.log(store) 11 // subscript是个订阅函数,他在状态发生变化的时候,自动调用 12 store.subscribe(() => { 13 console.log(store.getState()) 14 }) 15 16 // 调用store.dispatch, 会再次执行reducer 17 setInterval(() => { 18 store.dispatch({ 19 type: 'increment', 20 //负载,载荷 21 payload: 4 22 }) 23 }, 1000)
2.Statethis
Store对象包含全部数据。若是想的获得某个时点的数据,就要对Store生成快照。这种时点的数据集合,就叫State。当前时刻的State,能够经过store.getState()拿到。spa
一个State对应一个View,只要State相同,View就相同。设计
3.Action3d
View经过Action致使State发生变化
store.dispatch()是View发出Action的惟一方法。携带一个Action对象做为参数,将它发送出去。
Action是一个对象。其中的type属性是必须的,表示Action的名称。payload是它携带的信息。
能够这样理解,Action描述当前发生的事情。改变State的惟一办法,就是使用Action。他会运送数据到Store。
Action Creator: view要发送多少种消息,就会有多少种Action。经过Action Creator函数来生成Action
4.reducer
reducer就是实现(state,action)=> newState的纯函数--正真处理state的地方。不修改原来的state,而是经过返回新的state的方式去修改。
纯函数 一样的输入必定会有一样的输出
const reducer = (state = defaultState, action) => { // redux会在开始的时候执行一次reducer, action.type = @@redux/INITc.v.p.a.u.f if (action.type === 'increment') { return { //state = 1 直接修改state不容许 state + 1 能够 //state定义对象,在这里返回的时候也要返回对象 count: state.count + action.payload } } return state }
撸到这里是否是有点云里雾里,
下面来看一个redux实现的加减栗子
Counter.js
import React, { Component } from 'react' import store from './store' class Counter extends Component { constructor (props) { super(props) this.increment = this.increment.bind(this) this.decrement = this.decrement.bind(this) this.state = { count: store.getState() } store.subscribe(this.changeCount.bind(this)) } render () { return ( <div> <button onClick={this.decrement}>-</button> { this.state.count } <button onClick={this.increment}>+</button> </div> ) } increment () { store.dispatch({ type: 'increment' }) } decrement () { store.dispatch({ type: 'decrement' }) } changeCount () { this.setState({ count: store.getState() }) } } export default Counter
store.js
import { createStore } from 'redux' const defaultState = 1 const reducer = (state = defaultState, action) => { switch (action.type) { case 'increment' : return state + 1 case 'decrement' : return state - 1 default : return state } } const store = createStore(reducer) export default store