react-redux
store:圖書管理員
Component:借書用戶
Action:用戶說的話(要借什么書)
Reducer:記錄本
Store
//安裝Redux
yarn add redux
在src目錄下新建一個(gè)名為store的文件夾,并創(chuàng)建一個(gè)index.js,此為store倉庫的內(nèi)容區(qū)域。基本步驟如下:
//1. 從redux中導(dǎo)入一個(gè)createStore的方法。
import {createStore} from 'redux';
//2. 創(chuàng)建一個(gè)store
const store = createStore();
//3. 暴露模塊
export default store
有了倉庫store后,必須同時(shí)把reducer傳給store。
只有store的話,他什么都不知道,所以創(chuàng)建一個(gè)reducer:
//1. 在store的同級(jí)目錄下新建一個(gè)reducer.js
//在redux中,reducer需要返回一個(gè)函數(shù)
const defaultState = {} //默認(rèn)什么數(shù)據(jù)都不存儲(chǔ)
export default (state = defaultState,action)=>{ //state:整個(gè)store倉庫里的數(shù)據(jù)
//還需返回一個(gè)內(nèi)容,先默認(rèn)返回state;
return state;
}
store.subscribe() //訂閱
reducer
==reducer可以接受state==,但絕不可以修改state
- 創(chuàng)建好reducer后,將其傳遞給store
import reducer from './reducer'
- 創(chuàng)建store的時(shí)候,把reducer傳遞給store
const store = createStore();
- reducer存儲(chǔ)著整個(gè)項(xiàng)目應(yīng)用中的數(shù)據(jù),這時(shí)候store就知道了倉庫里數(shù)據(jù)有多少。
- 可以去reducer里查看,reducer管理倉庫里的數(shù)據(jù)(怎么處理,怎么存)
- reducer必須返回一個(gè)函數(shù)。
action(改變store的數(shù)據(jù),做通信)
//創(chuàng)建一個(gè)action
const action = { //借書的同學(xué)說的一句話,
type:'change_input_value', //type說的話,值是你幫我去改變input的值
value:e.target.value //這個(gè)值應(yīng)該是這處的value
}
dispatch
store通過dispatch把a(bǔ)ction傳遞給store,但此時(shí)store不知道該怎么處理,所以又會(huì)去找reducer,store會(huì)把當(dāng)前的prevState和action傳給reducer。
redux會(huì)自動(dòng)把store里的prevState和action傳給reducer
//
store.diapatch(action); //action傳給store
此時(shí)reducer拿到了數(shù)據(jù)后,對(duì)數(shù)據(jù)進(jìn)行處理
因?yàn)?strong>reducer可以接受state,但絕不可以修改state**,所以給state做一個(gè)深拷貝,這是固定的做法。最后把拷貝的數(shù)據(jù)return 出去。(return以后,返回給了store)