最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

簡易的redux?createStore手寫實現(xiàn)示例

 更新時間:2022年10月24日 16:38:33   作者:默海笑  
這篇文章主要介紹了簡易的redux?createStore手寫實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

1.首先創(chuàng)建一個store

沙箱鏈接

根目錄創(chuàng)建一個store文件夾,下面創(chuàng)建一個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對象并且導出
const state = createStore(reducer);
export default state;

結合上面的代碼分析

  • 創(chuàng)建store是redux庫的createStore函數(shù)接收一個reducer函數(shù)進行創(chuàng)建。
import { createStore } from '../my-redux'
  • 先手寫一個簡單的reducer函數(shù)
// 書寫reducer函數(shù)
狀態(tài)值默認為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導出
// 使用createStore(reducer)創(chuàng)建store對象并且導出
const state = createStore(reducer);
export default state;

2.其次創(chuàng)建一個my-redux

  • 將所有的函數(shù)都導入index.js

import createStore from './createStore'
export {
    createStore
}
  • 創(chuàng)建一個createStore.js
export default function createStore(reducer) {
    let currentState; // 當前state值
    let currentListeners = []; // store訂閱要執(zhí)行的函數(shù)儲存數(shù)組
    // 獲得當前state值
    function getState() {
        return currentState;
    }
    // 更新state
    function dispatch(action) {
        // 傳入action 調用reducer更新state值
        currentState = reducer(currentState, action)
        // 遍歷調用訂閱的函數(shù)
        currentListeners.forEach((listener) => listener());
    }
    // 將訂閱事件儲存到currentListeners數(shù)組,并返回unsubscribe 函數(shù)來取消訂閱
    function subscribe(listener) {
        currentListeners.push(listener);
        // unsubscribe 
        return () => {
            const index = currentListeners.indexOf(listener);
            currentListeners.splice(index, 1);
        };
    }
    dispatch({ type: "" }); // 自動dispatch一次,保證剛開始的currentState值等于state初始值
    // 返回store對象
    return {
        getState,
        dispatch,
        subscribe,
    }
}

可以根據(jù)上面給出的代碼步步分析:

①明確createStore接收一個reducer函數(shù)作為參數(shù)。

②createStore函數(shù)返回的是一個store對象,store對象包含getState,dispatch,subscribe等方法。

  • 逐步書寫store上的方法

書寫getState()方法

返回值:當前狀態(tài)值

// 獲得當前state值
    function getState() {
        return currentState;
    }

書寫dispatch方法

接受參數(shù):action。

dispatch方法,做的事情就是:①調用reducer函數(shù)更新state。②調用store訂閱的事件函數(shù)。

currentState是當前狀態(tài)值,currentListeners是儲存訂閱事件函數(shù)的數(shù)組。

    // 更新state
    function dispatch(action) {
        // 傳入action 調用reducer更新state值
        currentState = reducer(currentState, action)
        // 遍歷調用訂閱的函數(shù)
        currentListeners.forEach((listener) => listener());
    }

書寫subscribe方法

接受參數(shù):一個函數(shù) 返回值:一個函數(shù),用于取消訂閱unsubscribe

    // 將訂閱事件儲存到currentListeners數(shù)組,并返回unsubscribe 函數(shù)來取消訂閱
    function subscribe(listener) {
        currentListeners.push(listener);
        // unsubscribe 
        return () => {
            const index = currentListeners.indexOf(listener);
            currentListeners.splice(index, 1); // 刪除函數(shù)
        };
    }

返回store對象

    // 返回store對象
    return {
        getState,
        dispatch,
        subscribe,
    }

特別注意:

初始進入createStore函數(shù)的時候,需要通過dipatch方法傳入一個獨一無二的action(reducer函數(shù)默認返回state)來獲取初始的store賦值給currentStore。

可以結合下面reducer的default項和createStore方法調用的dispatch來理解

 dispatch({ type: "" }); // 自動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)完成了。那接下來就是檢查我們寫的這玩意是否起作用沒有了。

3.創(chuàng)建一個Test組件進行檢測。

老規(guī)矩先拋全部代碼

import React, { Component } from 'react'
import store from './store' // 引入store對象
export default class Test extends Component {
    // 組件掛載之后訂閱forceUpdate函數(shù),進行強制更新
    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對象

3. 創(chuàng)建一個類組件,并且使用store.getState()獲得狀態(tài)值

<div>
    {/* 獲取store狀態(tài)值 */}
    <div>{store.getState()}</div>
    <button onClick={this.add}>+</button>
    <button onClick={this.inc}>-</button>
</div>

4. 書寫對應的點擊按鈕

    // 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>

這樣是不是就可以實現(xiàn)了呢?哈哈哈,傻瓜,你是不是猛點鼠標,數(shù)字還是0呢?

當然,這里我們只是更新了store,但是并沒有更新組件,狀態(tài)的改變可以導致組件更新,但是store又不是Test組件的狀態(tài)。

這里我們使用一個生命周期函數(shù)componentDidMount和store的訂閱函數(shù)進行更新組件的目的,使用componentWillUnmount和store的取消訂閱函數(shù)(訂閱函數(shù)的返回值)。

    // 組件掛載之后訂閱forceUpdate函數(shù),進行強制更新
    componentDidMount() {
        this.unsubscribe = store.subscribe(() => {
            this.forceUpdate()
        })
    }
    // 組件卸載后取消訂閱
    componentWillUnmount() {
        this.unsubscribe()
    }

好了。這里我們就真實實現(xiàn)了一個簡單的createStore函數(shù)來創(chuàng)建store。

以上就是簡易的redux createStore手寫實現(xiàn)示例的詳細內容,更多關于手寫redux createStore的資料請關注腳本之家其它相關文章!

相關文章

  • React-intl 實現(xiàn)多語言的示例代碼

    React-intl 實現(xiàn)多語言的示例代碼

    本篇文章主要介紹了React-intl 實現(xiàn)多語言的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • React Zustand狀態(tài)管理庫的使用詳解

    React Zustand狀態(tài)管理庫的使用詳解

    Zustand是一個為React和瀏覽器環(huán)境設計的輕量級狀態(tài)管理庫,由Vercel開發(fā),它特點包括輕量級、易用性、靈活性、可組合性和性能優(yōu)化,支持多種狀態(tài)管理模式和中間件,適合中小型項目,Zustand還支持TypeScript,提供類型安全的支持
    2024-09-09
  • 通過React-Native實現(xiàn)自定義橫向滑動進度條的 ScrollView組件

    通過React-Native實現(xiàn)自定義橫向滑動進度條的 ScrollView組件

    開發(fā)一個首頁擺放菜單入口的ScrollView可滑動組件,允許自定義橫向滑動進度條,且內部渲染的菜單內容支持自定義展示的行數(shù)和列數(shù),在內容超出屏幕后,渲染順序為縱向由上至下依次排列,對React Native橫向滑動進度條相關知識感興趣的朋友一起看看吧
    2024-02-02
  • react?hooks深拷貝后無法保留視圖狀態(tài)解決方法

    react?hooks深拷貝后無法保留視圖狀態(tài)解決方法

    這篇文章主要為大家介紹了react?hooks深拷貝后無法保留視圖狀態(tài)解決示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-06-06
  • React Router 5.1.0使用useHistory做頁面跳轉導航的實現(xiàn)

    React Router 5.1.0使用useHistory做頁面跳轉導航的實現(xiàn)

    本文主要介紹了React Router 5.1.0使用useHistory做頁面跳轉導航的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • 解決antd的Table組件使用rowSelection屬性實現(xiàn)多選時遇到的bug

    解決antd的Table組件使用rowSelection屬性實現(xiàn)多選時遇到的bug

    這篇文章主要介紹了解決antd的Table組件使用rowSelection屬性實現(xiàn)多選時遇到的bug問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • React組件性能提升實現(xiàn)方法詳解

    React組件性能提升實現(xiàn)方法詳解

    這篇文章主要介紹了React組件性能最佳優(yōu)化實踐分享,React組件性能優(yōu)化的核心是減少渲染真實DOM節(jié)點的頻率,減少Virtual?DOM比對的頻率,更多相關內容需要的朋友可以參考一下
    2023-03-03
  • React?中使用?Redux?的?4?種寫法小結

    React?中使用?Redux?的?4?種寫法小結

    這篇文章主要介紹了在?React?中使用?Redux?的?4?種寫法,Redux 一般來說并不是必須的,只有在項目比較復雜的時候,比如多個分散在不同地方的組件使用同一個狀態(tài),本文就React使用?Redux的相關知識給大家介紹的非常詳細,需要的朋友參考下吧
    2022-06-06
  • React中使用setInterval函數(shù)的實例

    React中使用setInterval函數(shù)的實例

    這篇文章主要介紹了React中使用setInterval函數(shù)的實例,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • React路由攔截模式及withRouter示例詳解

    React路由攔截模式及withRouter示例詳解

    這篇文章主要為大家介紹了React路由攔截模式及withRouter示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08

最新評論

开化县| 都匀市| 湘潭市| 英山县| 新晃| 米易县| 黔东| 拜泉县| 安乡县| 怀化市| 彭阳县| 西盟| 锦州市| 朔州市| 怀柔区| 侯马市| 康保县| 南宫市| 栾城县| 聂拉木县| 遵化市| 新巴尔虎右旗| 武夷山市| 海宁市| 青冈县| 元氏县| 隆德县| 吴江市| 淮安市| 金秀| 乐昌市| 杭锦旗| 蒙自县| 安化县| 合水县| 新晃| 饶平县| 西城区| 哈密市| 星子县| 陇南市|