redux【react】

首先介紹一下redux就是Flux的一種進階實現。它是一個應用數據流框架,主要做用應用狀態的管理javascript

1、設計思想:java

(1)、web應用就是一個狀態機,視圖和狀態一一對應web

(2)、全部的狀態保存在一個對象裏面redux

2、三大原則:服務器

(1)、單一數據源框架

整個store被儲存在一個Object tree(對象樹)中,而且這個Object tree只存在於惟一一個store中函數

(2)、state是隻讀的this

惟一改變state的方法就是觸發action,action是一個用於描述已發生事件的普通對象spa

(3)、使用純函數來修改(reducer)設計

爲了描述action如何改變state tree,你須要編寫reducers

3、redux適用的場景

 

(1)、用戶的使用方式複雜

(2)、不一樣身份的用戶有不一樣的使用方式(好比普通用戶和管理員)

(3)、多個用戶之間能夠協做

(4)、與服務器大量交互,或者使用了WebSocket

(5)、View要從多個來源獲取數據

當項目多交互、多數據源的時候必須用到redux

從組件的角度來看何時用到redux

(1)、某個組件的狀態,須要共享

(2)、某個狀態須要在任何地方均可以拿到

(3)、一個組件須要改變全局狀態

(4)、一個組件須要改變另外一個組件的狀態

4、redux的工做流程

 

5、建立store

(1)、安裝 yarn add redux --dev

(2)、引入 import { createStore } from "redux";

(3)、建立一個store = createStore(reducer)

應用createStore建立store  createStore中必須傳遞一個reducer

import {createStore} from  "redux";


import  reducer  from  "./reducer";


const  store = createStore(reducer); 

6、建立reducer.js

const  defaultState={}


export default (state=defaultState,action)=>{
             return  state;

} 

 

這個函數裏面有2個參數一個是state,另外一個是action。

state指的是store中的數據

action指的是View修改數據的時候傳遞過來的action

這個函數必須返回一個新的數據,並且還不能對老的數據進行修改(Reducer函數中不能改變state,必須返回一個全新的對象)

咱們能夠先把這個state設置一個默認值defaultState。在defaultState這個對象中咱們能夠定義一些初始的數據

7、導出Store

import {createStore} from  "redux";


import  reducer  from  "./reducer";


const  store = createStore(reducer); 


export  default  store;

導出的store這個對象中默認自帶了一些方法

(1)、dispatch:用來傳遞action

(2)、getState:返回值就至關於this.state中的數據,裏面存放着公共的數據

(3)、replaceReducer:

(4)、subscribe:監聽數據的改變,必須傳遞一個函數

(5)、Symbol(observable):

8、建立action

let  action={
    type:「NUM__ADD」
}  

9、將Action傳遞給store  

 

store.dispatch(action)

 

10、監聽數據的改變

store.subscribe()

實例:

constructor(){
    super();
    store.subscribe(this.handUPdate.bind(this))

}

handleUpdate(){

   this.setState(store.getState())
}

   11、如何將reducer拆分紅多個reducers

(1)、引入combineReducers

import { combineReducers, createStore } from "redux";

(2)、合併多個reducers

let reducer = combineReducers({ todoReducers, tabReducers })

(3)、建立store

let store = createStore(reducer)

 

一、reducer.js

const defaultState={
    n:10
}

export default (state=defaultState,action)=>{

      return  state;
}


二、inforeducer.js

const defaultState={
      name:"張三",
n:20 } export default (state=defaultState,action)=>{ return state; } 三、store index.js import {createStore,combineReducers} from 「redux」 import reducer from "./reducers/reducer" import inforeducer from "./reducers/reducer" let reducer = combineReducers ({ reducer inforeducer }) let store = createStore(reducer) export default store;
四、APP.js
let {n} =this.state.reducer

注意:在使用state的時候要注意使用的誰的state  

總結一下:

     redux數據傳遞流程

        一、經過store.getState獲取到store中的數據,在頁面進行渲染

        二、當組件中須要修改數據的時候經過調用store中的dispatch方法來將acton傳遞給store 可是store偷偷給了reducer

        三、reducer的函數中接收到action,作業務邏輯處理 處理完畢後返回新的state

        四、時間訂閱  經過store中的subscribe方法來作事件的訂閱,當數據發生改變的時候組件中的數據更新

相關文章
相關標籤/搜索