簡(jiǎn)易的redux?createStore手寫實(shí)現(xiàn)示例
1.首先創(chuàng)建一個(gè)store
根目錄創(chuàng)建一個(gè)store文件夾,下面創(chuàng)建一個(gè)index.js

import { createStore } from '../my-redux'
// 書寫reducer函數(shù)
function reducer(state = 0, action) {
switch (action.type) {
case "add":
return state + 1;
case "inc":
return state - 1;
default:
return state;
}
}
// 使用createStore(reducer)創(chuàng)建store對(duì)象并且導(dǎo)出
const state = createStore(reducer);
export default state;
結(jié)合上面的代碼分析
- 創(chuàng)建store是redux庫(kù)的createStore函數(shù)接收一個(gè)reducer函數(shù)進(jìn)行創(chuàng)建。
import { createStore } from '../my-redux'
- 先手寫一個(gè)簡(jiǎn)單的reducer函數(shù)
// 書寫reducer函數(shù)
狀態(tài)值默認(rèn)為0
function reducer(state = 0, action) {
switch (action.type) {
case "add":
return state + 1;
case "inc":
return state - 1;
default:
return state;
}
}
- 將創(chuàng)建的store導(dǎo)出
// 使用createStore(reducer)創(chuàng)建store對(duì)象并且導(dǎo)出 const state = createStore(reducer); export default state;
2.其次創(chuàng)建一個(gè)my-redux

- 將所有的函數(shù)都導(dǎo)入index.js

import createStore from './createStore'
export {
createStore
}
- 創(chuàng)建一個(gè)createStore.js
export default function createStore(reducer) {
let currentState; // 當(dāng)前state值
let currentListeners = []; // store訂閱要執(zhí)行的函數(shù)儲(chǔ)存數(shù)組
// 獲得當(dāng)前state值
function getState() {
return currentState;
}
// 更新state
function dispatch(action) {
// 傳入action 調(diào)用reducer更新state值
currentState = reducer(currentState, action)
// 遍歷調(diào)用訂閱的函數(shù)
currentListeners.forEach((listener) => listener());
}
// 將訂閱事件儲(chǔ)存到currentListeners數(shù)組,并返回unsubscribe 函數(shù)來(lái)取消訂閱
function subscribe(listener) {
currentListeners.push(listener);
// unsubscribe
return () => {
const index = currentListeners.indexOf(listener);
currentListeners.splice(index, 1);
};
}
dispatch({ type: "" }); // 自動(dòng)dispatch一次,保證剛開始的currentState值等于state初始值
// 返回store對(duì)象
return {
getState,
dispatch,
subscribe,
}
}
可以根據(jù)上面給出的代碼步步分析:
①明確createStore接收一個(gè)reducer函數(shù)作為參數(shù)。
②createStore函數(shù)返回的是一個(gè)store對(duì)象,store對(duì)象包含getState,dispatch,subscribe等方法。
- 逐步書寫store上的方法
書寫getState()方法
返回值:當(dāng)前狀態(tài)值
// 獲得當(dāng)前state值
function getState() {
return currentState;
}
書寫dispatch方法
接受參數(shù):action。
dispatch方法,做的事情就是:①調(diào)用reducer函數(shù)更新state。②調(diào)用store訂閱的事件函數(shù)。
currentState是當(dāng)前狀態(tài)值,currentListeners是儲(chǔ)存訂閱事件函數(shù)的數(shù)組。
// 更新state
function dispatch(action) {
// 傳入action 調(diào)用reducer更新state值
currentState = reducer(currentState, action)
// 遍歷調(diào)用訂閱的函數(shù)
currentListeners.forEach((listener) => listener());
}
書寫subscribe方法
接受參數(shù):一個(gè)函數(shù) 返回值:一個(gè)函數(shù),用于取消訂閱unsubscribe
// 將訂閱事件儲(chǔ)存到currentListeners數(shù)組,并返回unsubscribe 函數(shù)來(lái)取消訂閱
function subscribe(listener) {
currentListeners.push(listener);
// unsubscribe
return () => {
const index = currentListeners.indexOf(listener);
currentListeners.splice(index, 1); // 刪除函數(shù)
};
}
返回store對(duì)象
// 返回store對(duì)象
return {
getState,
dispatch,
subscribe,
}
特別注意:
初始進(jìn)入createStore函數(shù)的時(shí)候,需要通過(guò)dipatch方法傳入一個(gè)獨(dú)一無(wú)二的action(reducer函數(shù)默認(rèn)返回state)來(lái)獲取初始的store賦值給currentStore。
可以結(jié)合下面reducer的default項(xiàng)和createStore方法調(diào)用的dispatch來(lái)理解
dispatch({ type: "" }); // 自動(dòng)dispatch一次,保證剛開始的currentState值等于state初始值
// 書寫reducer函數(shù)
function reducer(state = 0, action) {
switch (action.type) {
case "add":
return state + 1;
case "inc":
return state - 1;
default:
return state;
}
}
這樣我們的createStore函數(shù)就已經(jīng)完成了。那接下來(lái)就是檢查我們寫的這玩意是否起作用沒有了。
3.創(chuàng)建一個(gè)Test組件進(jìn)行檢測(cè)。

老規(guī)矩先拋全部代碼
import React, { Component } from 'react'
import store from './store' // 引入store對(duì)象
export default class Test extends Component {
// 組件掛載之后訂閱forceUpdate函數(shù),進(jìn)行強(qiáng)制更新
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
this.forceUpdate()
})
}
// 組件卸載后取消訂閱
componentWillUnmount() {
this.unsubscribe()
}
// handleclick事件函數(shù)
add = () => {
store.dispatch({ type: 'add' });
console.log(store.getState());
}
inc = () => {
store.dispatch({ type: 'inc' });
console.log(store.getState());
}
render() {
return (
<div>
{/* 獲取store狀態(tài)值 */}
<div>{store.getState()}</div>
<button onClick={this.add}>+</button>
<button onClick={this.inc}>-</button>
</div>
)
}
}
1. 將Test組件記得引入App根組件
import Test from './Test';
function App() {
return (
<div className="App">
<Test />
</div>
);
}
export default App;
2. 將store引入Test組件
import React, { Component } from 'react'
import store from './store' // 引入store對(duì)象
3. 創(chuàng)建一個(gè)類組件,并且使用store.getState()獲得狀態(tài)值
<div>
{/* 獲取store狀態(tài)值 */}
<div>{store.getState()}</div>
<button onClick={this.add}>+</button>
<button onClick={this.inc}>-</button>
</div>
4. 書寫對(duì)應(yīng)的點(diǎn)擊按鈕
// handleclick事件函數(shù)
add = () => {
store.dispatch({ type: 'add' });
console.log(store.getState());
}
inc = () => {
store.dispatch({ type: 'inc' });
console.log(store.getState());
}
<div>
{/* 獲取store狀態(tài)值 */}
<div>{store.getState()}</div>
<button onClick={this.add}>+</button>
<button onClick={this.inc}>-</button>
</div>
這樣是不是就可以實(shí)現(xiàn)了呢?哈哈哈,傻瓜,你是不是猛點(diǎn)鼠標(biāo),數(shù)字還是0呢?
當(dāng)然,這里我們只是更新了store,但是并沒有更新組件,狀態(tài)的改變可以導(dǎo)致組件更新,但是store又不是Test組件的狀態(tài)。
這里我們使用一個(gè)生命周期函數(shù)componentDidMount和store的訂閱函數(shù)進(jìn)行更新組件的目的,使用componentWillUnmount和store的取消訂閱函數(shù)(訂閱函數(shù)的返回值)。
// 組件掛載之后訂閱forceUpdate函數(shù),進(jìn)行強(qiáng)制更新
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
this.forceUpdate()
})
}
// 組件卸載后取消訂閱
componentWillUnmount() {
this.unsubscribe()
}
好了。這里我們就真實(shí)實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的createStore函數(shù)來(lái)創(chuàng)建store。
以上就是簡(jiǎn)易的redux createStore手寫實(shí)現(xiàn)示例的詳細(xì)內(nèi)容,更多關(guān)于手寫redux createStore的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
React-intl 實(shí)現(xiàn)多語(yǔ)言的示例代碼
本篇文章主要介紹了React-intl 實(shí)現(xiàn)多語(yǔ)言的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11
React Zustand狀態(tài)管理庫(kù)的使用詳解
Zustand是一個(gè)為React和瀏覽器環(huán)境設(shè)計(jì)的輕量級(jí)狀態(tài)管理庫(kù),由Vercel開發(fā),它特點(diǎn)包括輕量級(jí)、易用性、靈活性、可組合性和性能優(yōu)化,支持多種狀態(tài)管理模式和中間件,適合中小型項(xiàng)目,Zustand還支持TypeScript,提供類型安全的支持2024-09-09
通過(guò)React-Native實(shí)現(xiàn)自定義橫向滑動(dòng)進(jìn)度條的 ScrollView組件
開發(fā)一個(gè)首頁(yè)擺放菜單入口的ScrollView可滑動(dòng)組件,允許自定義橫向滑動(dòng)進(jìn)度條,且內(nèi)部渲染的菜單內(nèi)容支持自定義展示的行數(shù)和列數(shù),在內(nèi)容超出屏幕后,渲染順序?yàn)榭v向由上至下依次排列,對(duì)React Native橫向滑動(dòng)進(jìn)度條相關(guān)知識(shí)感興趣的朋友一起看看吧2024-02-02
react?hooks深拷貝后無(wú)法保留視圖狀態(tài)解決方法
這篇文章主要為大家介紹了react?hooks深拷貝后無(wú)法保留視圖狀態(tài)解決示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
React Router 5.1.0使用useHistory做頁(yè)面跳轉(zhuǎn)導(dǎo)航的實(shí)現(xiàn)
本文主要介紹了React Router 5.1.0使用useHistory做頁(yè)面跳轉(zhuǎn)導(dǎo)航的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
解決antd的Table組件使用rowSelection屬性實(shí)現(xiàn)多選時(shí)遇到的bug
這篇文章主要介紹了解決antd的Table組件使用rowSelection屬性實(shí)現(xiàn)多選時(shí)遇到的bug問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
React?中使用?Redux?的?4?種寫法小結(jié)
這篇文章主要介紹了在?React?中使用?Redux?的?4?種寫法,Redux 一般來(lái)說(shuō)并不是必須的,只有在項(xiàng)目比較復(fù)雜的時(shí)候,比如多個(gè)分散在不同地方的組件使用同一個(gè)狀態(tài),本文就React使用?Redux的相關(guān)知識(shí)給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-06-06
React中使用setInterval函數(shù)的實(shí)例
這篇文章主要介紹了React中使用setInterval函數(shù)的實(shí)例,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04

