react redux狀態管理

2021-08-27 05:54:44 字數 1174 閱讀 9228

redux 的適用場景:多互動、多資料來源。

redux用乙個單獨的常量狀態樹(物件)儲存這一整個應用的狀態,這個物件不能直接被改變。當一些資料變化了,乙個新的物件就會被建立(使用actions和reducers)。

redux 是乙個范用的狀態管理框架

主要是解決了元件間狀態共享的問題

原理是集中式管理

redux中有三個基本概念,action,reducer,store。

store 倉庫

維持應用的 state;

提供 getstate() 方法獲取 state;

提供 dispatch(action) 方法更新 state;

通過 subscribe(listener) 註冊***。

action 中傳送過來的物件 必須有乙個type屬性

reducer 他是乙個純函式 他會跟action傳送過來的type型別做邏輯上的處理(使用switch方法進行判斷)

安裝 npm install redux -d

引入必要元件:

import from 'redux';

生成store:

const store = createstore(reducer, state初始狀態[可選]);

取得當前時刻的state:

const state = store.getstate();

發出action

store.dispatch();

設定監聽函式:

store.subscribe(callback);

reducer 函式最重要的特徵是,它是乙個純函式。也就是說,只要是同樣的輸入,必定得到同樣的輸出。

約束:不得改寫引數

不能呼叫系統 i/o 的api

不能呼叫date.now()或者math.random()等不純的方法,因為每次會得到不一樣的結果

reducer 函式裡面不能改變 state,必須返回乙個全新的物件,請參考下面的寫法。

// state 是乙個物件

function reducer(state, action) , state, );

// 或者

return ;

}// state 是乙個陣列

function reducer(state, action)

react redux使用小結

總結 需要使用的庫redux,react redux,react router redux 使用乙個react redux 的庫使得redux的使用更簡潔,它提供了provider和connect方法 先在入口檔案內使用 元件 provider 這裡使用了redux中的重要組成部分store,所以下...

react redux使用小結

總結 需要使用的庫redux,react redux,react router redux 使用乙個react redux 的庫使得redux的使用更簡潔,它提供了provider和connect方法 先在入口檔案內使用 元件 provider 這裡使用了redux中的重要組成部分store,所以下...

React ,Redux 教程彙總

學習react redux大概半個月了,總結一下看過的資料,此教程比較適合新手。一.中文資料 1.w3cschool教程 傳送門 2.react 入門例項教程 阮一峰,2015 03 一篇全面又易懂的react 入門教程。只需要跟著做一遍,就能初步掌握react。傳送門 1,2當中可以任選乙個看。3...