基本介紹
- 單向數(shù)據(jù)流:從父組件流向子組件盹廷,兄弟組件無(wú)法共享數(shù)據(jù)
- State:React中的狀態(tài)砰碴,是只讀對(duì)象(react可以用個(gè)setState更改)
- Reducer: 基本函數(shù)荐吵,用于對(duì)State的業(yè)務(wù)處理
- Action: 普通對(duì)象,用于描述事件行為,改變State
store(數(shù)據(jù)源)=> component => action => reducer =>store(全新數(shù)據(jù)源)
安裝
yarn add redux --save
yarn add react-redux --save
redux集成
- 創(chuàng)建Action模塊
- 創(chuàng)建Reducer模塊
- 創(chuàng)建Store模塊
- 通過(guò)connect方法將React組件和Redux連接起來(lái)
- 添加Provider作為項(xiàng)目的根組件食侮,用于數(shù)據(jù)的存儲(chǔ)x
Redux調(diào)試工具安裝
-
在Chrome中安裝Redux Devtools擴(kuò)展
yarn add redux-devtools-extension
項(xiàng)目中使用(基于react學(xué)習(xí)筆記的項(xiàng)目==reactAntBike => 編寫(xiě)菜單切換文字)
1. 在src中創(chuàng)建redux的文件夾荷并,并添加index.js文件
image.png
-
第一步: 創(chuàng)建action行為合砂,在action目錄下創(chuàng)建index.js
image.png -
第二步:創(chuàng)建對(duì)action數(shù)據(jù)源的數(shù)據(jù)處理,在reducer下創(chuàng)建index.js
image.png -
第三步:創(chuàng)建數(shù)據(jù)源store源织,在store文件夾下創(chuàng)建index.js
image.png -
第四步:在總index.js下引入provider翩伪,將react與redux的數(shù)據(jù)相結(jié)合
image.png
這樣在控制臺(tái)就可以查看react
image.png
2. 在菜單中添加選中高亮
-
第一步:獲取當(dāng)前地址
image.png -
第二步:給menu組件綁定點(diǎn)擊事件以及設(shè)置選中值
image.png
image.png
3. 將點(diǎn)擊的菜單名稱記錄在redux中
-
第一步:引入redux
import { connect } from 'react-redux' // 通過(guò)connect將react和redux相連 import { switchMenu } from './../../redux/action' // 引用觸發(fā)事件行為
-
第二步:將組件放進(jìn)redux里
去掉定義NavLeft的export default,在低端導(dǎo)出
image.png
-
第三步:在菜單點(diǎn)擊事件中谈息,將點(diǎn)擊的菜單名稱存儲(chǔ)在redux中
注意缘屹,item變成對(duì)象,所以當(dāng)前選中高亮要變成item.props.eventKey
image.png
4. 在header組件中獲取redux的數(shù)據(jù)源
-
第一步:在組件中引用redux,并將export換成connect方式侠仇,并從redux中獲取數(shù)據(jù)
image.png
image.png
-
第二步:賦值
image.png
這樣就可以切換+高亮了