使用react+redux實現(xiàn)計數(shù)器功能及遇到問題
Redux,本身就是一個單純的狀態(tài)管理者,我們不追溯它的歷史,從使用角度來說:它提供一個全局的對象store,store中包含state對象用以包含所有應用數(shù)據(jù),并且store提供了一些reducer方法。這些方法可以自定義,使用調(diào)用者得以改變state的值。state的值僅為只讀,如果需要更改則必須只能通過reducer。
Redux
- 核心對象:store
- 數(shù)據(jù)存儲:state
- 狀態(tài)更新提交接口:==dispatch==
- 狀態(tài)更新提交參數(shù):帶type和payload的==Action==
- 狀態(tài)更新計算:==reducer==
- 限制:reducer必須是純函數(shù),不支持異步
- 特性:支持中間件
React + Redux
在recat中不使用redux 時遇到的問題
在react中組件通信的數(shù)據(jù)是單向的,頂層組件可以通過props屬性向下層組件傳遞數(shù)據(jù),而下層組件不能向上層組件傳遞數(shù)據(jù),要實現(xiàn)下層組件修改數(shù)據(jù),需要上層組傳遞修改數(shù)據(jù)的方法到下層組件,當項目越來越的時候,組件之間傳遞數(shù)據(jù)變得越來越困難
在react中加入redux 的好處
使用redux管理數(shù)據(jù),由于Store獨立于組件,使得數(shù)據(jù)管理獨立于組件,解決了組件之間傳遞數(shù)據(jù)困難的問題
使用redux
下載redux
npm install redux react-redux
redux 工作流程
- 組件通過 dispatch 觸發(fā)action
- store 接受 action 并將 action 分發(fā)給 reducer
- reducer 根據(jù) action 類型對狀態(tài)進行更改并將更改后的數(shù)據(jù)返回給store
- 組件訂閱了store中的狀態(tài),store中的狀態(tài)更新會同步到組件
使用react+redux實現(xiàn)計數(shù)器
1.創(chuàng)建項目,并安裝 redux
# 如果沒有安裝react腳手架則執(zhí)行這條命令安裝reate腳手架 npm install -g create-react-app # 創(chuàng)建reate項目 create-react-app 項目名 # 進入項目 cd 項目名 # 安裝 redux npm install redux reate-redux
2.引入redux,并根據(jù)開始實現(xiàn)的代碼在react中實現(xiàn)計數(shù)器
//index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { createStore } from 'redux'; const initialState = { count: 0 } function reducer(state = initialState, action) { switch (action.type) { case 'increment': return { count: state.count + 1 } case 'decrement': return { count: state.count - 1 } default: return state } } const store = createStore(reducer) const increment = { type: 'increment' } const decrement = { type: 'decrement' } function Count() { return <div> <button onClick={() => store.dispatch(increment)}>+</button> <span>{store.getState().count}</span> <button onClick={() => store.dispatch(decrement)}>-</button> </div> } store.subscribe( () => { console.log(store.getState()) ReactDOM.render( <React.StrictMode> <Count /> </React.StrictMode>, document.getElementById('root') ); }) ReactDOM.render( <React.StrictMode> <Count /> </React.StrictMode>, document.getElementById('root') );
明顯以上方式雖然可以實現(xiàn)計數(shù)器的功能,但在實際項目中肯定不能這樣使用,因為組件一般都在單獨的文件中的,這種方式明顯在其他組件中并不能獲取到Store。
計數(shù)器案例代碼優(yōu)化-讓store全局可訪問
為了解決Store獲取問題需要使用react-redux來解決這個問題,react-redux給我們提供了Provider組件和connect方法
Provide 組件
是一個組件 可以吧創(chuàng)建出來的store 放在一個全局的地方,讓組件可以拿到store,通過provider組件,將 store 放在了全局的組件可以夠的到的地方 ,provider要求我們放在最外層組件
connect
connect 幫助我們訂閱store中的狀態(tài),狀態(tài)發(fā)生改變后幫助我們重新渲染組件
通過 connect 方法我們可以拿到 store 中的狀態(tài) 把 store 中的狀態(tài)映射到props中
通過 connect 方法可以拿到 dispatch 方法
connect 的參數(shù)為一個函數(shù) 這個函數(shù)可以拿到store中的狀態(tài),要求我們這個函數(shù)必須返回一個對象,在這個對象中寫的內(nèi)容都會映射給組件的props屬性
connect 調(diào)用后返回一個函數(shù) 返回的這個函數(shù)繼續(xù)調(diào)用需要傳入組件告訴connect需要映射到那個組件的props
新建 Component 文件夾、創(chuàng)建 Count.js 文件
import React from 'react' function Count() { return <div> <button onClick={() => store.dispatch(increment)}>+</button> <span>{store.getState().count}</span> <button onClick={() => store.dispatch(decrement)}>-</button> </div> } export default Count
引入 Provider 組件放置在最外層,并制定store
ReactDOM.render( // 通過provider組件 將 store 放在了全局的組件可以夠的到的地方 provider要求我們放在最外層組件 <Provider store={store}><Count /></Provider>, document.getElementById('root') );
引入 connect 方法 根據(jù) connect 的使用來包裹組件
const mapStateProps = state => ({ count: state.count, a: '1' }) // connect 的參數(shù)為一個函數(shù) 這個函數(shù)可以拿到store中的狀態(tài),要求我們這個函數(shù)必須返回一個對象,在這個對象中寫的內(nèi)容都會映射給組件的props屬性 // connect 調(diào)用后返回一個函數(shù) 返回的這個函數(shù)繼續(xù)調(diào)用需要傳入組件告訴connect需要映射到那個組件的props export default connect(mapStateProps)(Count)
改造 Count 組件把 action 復制到該文件中
const increment = { type: 'increment' } const decrement = { type: 'decrement' } function Count({count,dispatch}) { return <div> <button onClick={() => {dispatch(increment)}}>+</button> <span>{count}</span> <button onClick={() => {dispatch(decrement)}}>-</button> </div> }
現(xiàn)在項目已經(jīng)可以運行了但是Count組件中的 提交Action的那一長串代碼影響視圖的可讀性,所以代碼還是需要優(yōu)化
計數(shù)器案例代碼優(yōu)化-讓視圖中的代碼可讀性更高
我們希望視圖中直接調(diào)用一個函數(shù)這樣視圖代碼可讀性強,這個需要利用connect的第二個參數(shù),第二個參數(shù)是一個函數(shù),這個函數(shù)的形參就是dispatch方法,要求這個函數(shù)返回一個對象,返回的這個對象中的內(nèi)容都會映射到組件的props屬性上
申明一個變量為connect中的第二個參數(shù),在這個變量中返回執(zhí)行不同action操作的對象
// connect 的第二個參數(shù) 這個參數(shù)是個函數(shù) 這個函數(shù)的形參就是dispatch方法 要求返回一個對象 這個對象中的屬性會被映射到組件的props上 const mapDispatchToProps = dispatch => ({ increment (){ dispatch({ type: 'increment' }) }, decrement (){ dispatch({ type: 'decrement' }) } }) // connect 的參數(shù)為一個函數(shù) 這個函數(shù)可以拿到store中的狀態(tài),要求我們這個函數(shù)必須返回一個對象,在這個對象中寫的內(nèi)容都會映射給組件的props屬性 // connect 調(diào)用后返回一個函數(shù) 返回的這個函數(shù)繼續(xù)調(diào)用需要傳入組件告訴connect需要映射到那個組件的props export default connect(mapStateProps, mapDispatchToProps)(Count)
在組件中結(jié)構(gòu)props在視圖中直接綁定事件
function Count({count,increment,decrement}) { return <div> <button onClick={increment}>+</button> <span>{count}</span> <button onClick={decrement}>-</button> </div> }
通過這次優(yōu)化我們發(fā)現(xiàn) 調(diào)用 dispatch 觸發(fā)action 的方法的代碼都是重復的,所以還需要繼續(xù)優(yōu)化
優(yōu)化調(diào)用 dispatch 觸發(fā)action 的方法的重復代碼簡化
利用 bindActionCreators 來簡化 dispatch 觸發(fā) action的操作,bindActionCreators來幫助我們生成執(zhí)行action動作的函數(shù)
bindActionCreators 有兩個參數(shù),第一個參數(shù)為 執(zhí)行action的對象,第二個參數(shù)為 dispatch方法
分離action操作,新建store/actions/counter.actions.js文件把執(zhí)行action操作單獨放在這個文件并導出
export const increment = () => ({type: 'increment'}) export const decrement = () => ({type: 'decrement'})
在Count.js中導入關(guān)于計數(shù)器的action,用bindActionCreators方法來生成dispatch執(zhí)行action函數(shù)
import { bindActionCreators } from 'redux' import * as counterActions from './../store/actions/counter.actions' const mapDispatchToProps = dispatch => (bindActionCreators(counterActions, dispatch)) // connect 的參數(shù)為一個函數(shù) 這個函數(shù)可以拿到store中的狀態(tài),要求我們這個函數(shù)必須返回一個對象,在這個對象中寫的內(nèi)容都會映射給組件的props屬性 // connect 調(diào)用后返回一個函數(shù) 返回的這個函數(shù)繼續(xù)調(diào)用需要傳入組件告訴connect需要映射到那個組件的props export default connect(mapStateProps, mapDispatchToProps)(Count)
代碼優(yōu)化到這里我們發(fā)現(xiàn),redux的代碼與組件融合在一起,所以我需要拆分成獨立的,為什么要抽離redux呢?因為我們要讓我們的代碼結(jié)構(gòu)更加合理
重構(gòu)計數(shù)器,把redux相關(guān)代碼抽離
把reducer函數(shù)抽離為單獨的文件、把創(chuàng)建store抽離到單獨的文件中
因為在reducer 和 actions中我們都寫了字符串,但是字符串沒有提示所以我們把字符串定義成常量防止我們出現(xiàn)單詞錯誤這種低級錯誤,新建 src/store/const/counter.const.js 文件
export const INCREMENT = 'increment' export const DECREMENT = 'decrement'
新建 src/store/reducers/counter.reducers.js 文件把 reducer 函數(shù)抽離到此文件中
import { INCREMENT, DECREMENT} from './../const/counter.const' const initialState = { count: 0 } // eslint-disable-next-line import/no-anonymous-default-export export default (state = initialState, action) => { switch (action.type) { case INCREMENT: return { count: state.count + 1 } case DECREMENT: return { count: state.count - 1 } default: return state } }
更改actions中的字符串為引入變量
import { INCREMENT, DECREMENT} from './../const/counter.const' export const increment = () => ({type: INCREMENT}) export const decrement = () => ({type: DECREMENT})
創(chuàng)建src/store/index.js文件 ,在這個文件中創(chuàng)建store 并導出
import { createStore } from 'redux'; import reducer from './reducers/counter.reducers' export const store = createStore(reducer)
在引入store的文件中改變?yōu)闆_項目中store文件中引入store
import React from 'react'; import ReactDOM from 'react-dom'; import Count from './components/Count'; import { store } from './store' import { Provider } from 'react-redux' /** * react-redux 讓react 和 redux 完美結(jié)合 * Provider 是一個組件 可以吧創(chuàng)建出來的store 放在一個全局的地方 讓組件可以拿到store * connect 是一個方法 */ ReactDOM.render( // 通過provider組件 將 store 放在了全局的組件可以夠的到的地方 provider要求我們放在最外層組件 <Provider store={store}><Count /></Provider>, document.getElementById('root') );
為action 傳遞參數(shù),對計數(shù)器案例做擴展
這個計數(shù)器案例已經(jīng)實現(xiàn)了點擊按鈕加一減一操作了,現(xiàn)在有個新需求我們需要加減一個數(shù)值例如加五減五
這就需要對action傳遞參數(shù)了
在視圖中按鈕綁定函數(shù)傳入?yún)?shù)
function Count({count,increment,decrement}) { return <div> <button onClick={() => increment(5)}>+</button> <span>{count}</span> <button onClick={() => decrement(5)}>-</button> </div> }
在dispacth執(zhí)行action動作時接受參數(shù)并傳入到action中
export const increment = payload => ({type: INCREMENT, payload}) export const decrement = payload => ({type: DECREMENT, payload})
在reducers中接收參數(shù)并作相應處理
export default (state = initialState, action) => { switch (action.type) { case INCREMENT: return { count: state.count + action.payload } case DECREMENT: return { count: state.count - action.payload } default: return state } }
原文地址:https://kspf.xyz/archives/10/
到此這篇關(guān)于在react中使用redux并實現(xiàn)計數(shù)器案例的文章就介紹到這了,更多相關(guān)react redux實現(xiàn)計數(shù)器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React Draggable插件如何實現(xiàn)拖拽功能
這篇文章主要介紹了React Draggable插件如何實現(xiàn)拖拽功能問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07React?Refs?的使用forwardRef?源碼示例解析
這篇文章主要為大家介紹了React?之?Refs?的使用和?forwardRef?的源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11React實現(xiàn)createElement 和 cloneElement的區(qū)別
本文詳細介紹了React中React.createElement和React.cloneElement兩種方法的定義、用法、區(qū)別及適用場景,具有一定的參考價值,感興趣的可以了解一下2024-09-09使用webpack5從0到1搭建一個react項目的實現(xiàn)步驟
這篇文章主要介紹了使用webpack5從0到1搭建一個react項目的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12react中使用heatmap.js實現(xiàn)熱力圖的繪制
heatmap.js?是一個用于生成熱力圖的?JavaScript?庫,React?是一個流行的?JavaScript?庫,用于構(gòu)建用戶界面,本小編給大家介紹了在React?應用程序中使用heatmap.js實現(xiàn)熱力圖的繪制的示例,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-12-12