初識redux走向redux-react

廢話很少說,先上一張圖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
相關文章
相關標籤/搜索