Redux詳解

Redux是什么

  • Redux 是 JavaScript 狀態(tài)容器,提供可預(yù)測(cè)化的狀態(tài)管理。

使用場(chǎng)景

  • 用戶的使用方式復(fù)雜
  • 不同身份的用戶有不同的使用方式(比如普通用戶和管理員)
  • 多個(gè)用戶之間可以協(xié)作
  • 與服務(wù)器大量交互,或者使用了WebSocket
  • View要從多個(gè)來(lái)源獲取數(shù)據(jù)
  • 某個(gè)組件的狀態(tài),需要共享;某個(gè)狀態(tài)需要在任何地方都可以拿到;一個(gè)組件需要改變?nèi)譅顟B(tài);一個(gè)組件需要改變另一個(gè)組件的狀態(tài)

重要概念

  • state:store對(duì)象中的定義的初始數(shù)據(jù)(初始狀態(tài))。
  • action:
    • action是一個(gè)對(duì)象用來(lái)描述當(dāng)前發(fā)生的事情,action就是視圖View發(fā)出的通知,表示state要發(fā)生改變;
    • View 要發(fā)送多少種消息,就會(huì)有多少種 action;通過(guò)action creator(action 創(chuàng)建函數(shù))生成action,用來(lái)改變state狀態(tài)。
  • reducer
    • 定義state改變的規(guī)則即:store收到action后,必須給出新的state,這樣view才會(huì)發(fā)生變化;這種state的計(jì)算過(guò)程就叫做reducer;
    • reducer是一個(gè)純函數(shù),可以保證同樣的state,必定得到同樣的 view;reducer并不能改變state。
  • store:
    • 存儲(chǔ)數(shù)據(jù)或者說(shuō)是狀態(tài)的容器,整個(gè)應(yīng)用中只能有一個(gè)store;Redux提供createStore這個(gè)函數(shù)來(lái)生成store。
    • store.dispatch()View發(fā)出action的唯一方法,store.dispatch接受一個(gè) action 對(duì)象作為參數(shù),將它發(fā)送出去。

使用案例

  • 開(kāi)發(fā)中一般使用腳手架create-react-app來(lái)搭建項(xiàng)目,Reduc的項(xiàng)目結(jié)構(gòu)用如下:
├── store/              # Redux全局狀態(tài)管理倉(cāng)庫(kù)
        ├── index.js                # 生成store容器并導(dǎo)出的地方
        ├── state.js                # 全局?jǐn)?shù)據(jù)存儲(chǔ)state
        ├── actions.js              # 定義actions創(chuàng)建函數(shù)
        ├── action-types.js         # 定義action的type字符串常量
        ├── reducers.js             # reducer規(guī)則

state.js示例

//Redux全局初始狀態(tài)
export default {
    cityName: '北京',//定位地址 默認(rèn)北京
    userName: '',//用戶名
    id:[],
}

action-types.js示例

//所有actions函數(shù)的`type`字符串常量
export const STORE_UPDATE = 'STORE_UPDATE';
export const STORE_ADD = 'STORE_ADD';
export const STORE_RM = 'STORE_RM';

actions.js示例

//定義`action`創(chuàng)建函數(shù)生成`action`對(duì)象
import * as actionTypes from './action-types.js'

export function update(data) {
    return {
        type: actionTypes.STORE_UPDATE,
        data
    }
}

export function add(item) {
    return {
        type: actionTypes.STORE_ADD,
        data: item
    }
}

export function rm(item) {
    return {
        type: actionTypes.STORE_RM,
        data: item
    }
}

reducers.js示例

//定義Redux規(guī)則
import { combineReducers } from 'redux';
import * as actionTypes from './action-types.js';
import initialState from './state.js';

const userInfo = (state = initialState, action) => {
    switch (action.type) {
        case actionTypes.STORE_UPDATE:
            return action.data;
        case actionTypes.STORE_ADD:
            state.id.unshift(action.data.id);
            return state;
        case actionTypes.STORE_RM:
            state.id = state.id.filter(item => {
                if(item !== action.data.id) {
                    return state.id;
                }
            })
            return state;
        default:
            return state
    }
}

export default combineReducers({
    userInfo
})

index.js示例

//生成store容器

import { createStore } from 'redux';
import Reducers from './reducers';

export default function configureStore(initialState) {
    const store = createStore(Reducers,initialState,
        // 觸發(fā) redux-devtools
        window.devToolsExtension ? window.devToolsExtension() : undefined
    );
    return store;
}

在React框架中配合react-redux使用

App.js跟組件中

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import RouteMap from './router/router.jsx';
import configureStore from './store/index.js';

import './style/reset.scss';
import './style/font.scss';
import './style/common.scss';

//創(chuàng)建Redux的store對(duì)象
const store = configureStore();

class App extends Component {
    render() {
        return (
            <Provider store={store}>
                <RouteMap></RouteMap>
            </Provider>
        );
    }
}
export default App;

React組件中引入和改變r(jià)edux的狀態(tài)

import React, {Component} from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as userInfoActionsFromOtherFile from "../../../../store/actions";

// 使用redux存儲(chǔ)的狀態(tài)
    loginCheck = () => {
        const id = this.props.id
        const userInfo = this.props.userInfo
        if (!userInfo.userName) {
            this.props.history.push({
                pathname:'/login',
                state: {
                    router: `/detail/${id}`
                }
            })
            return false
        }
        return true
    }

//改變r(jià)edux狀態(tài)
storeHandle = () => {
        // 驗(yàn)證登錄,未登錄則return
        const loginFlag = this.loginCheck()
        if (!loginFlag) {
            return
        }

        const id = this.props.id
        const userInfoActions = this.props.userInfoActions
        if (this.state.isStore) {
            // 已經(jīng)被收藏了,則取消收藏
            userInfoActions.rm({id: id})
        } else {
            // 未收藏,則添加到收藏中
            userInfoActions.add({id: id})
        }
        // 修改狀態(tài)
        this.setState({
            isStore: !this.state.isStore
        })
    }

// -------------------redux react 綁定--------------------
function mapStateTopProps(state) {
    return {
        userInfo: state.userInfo,
    };
}
function mapDispatchToProps(dispatch) {
    return {
        userInfoActions: bindActionCreators(userInfoActionsFromOtherFile, dispatch)
    }
}

export default connect(
    mapStateTopProps,
    mapDispatchToProps
)(Buy);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 學(xué)習(xí)必備要點(diǎn): 首先弄明白,Redux在使用React開(kāi)發(fā)應(yīng)用時(shí),起到什么作用——狀態(tài)集中管理 弄清楚Redux是...
    賀賀v5閱讀 9,066評(píng)論 10 58
  • 看到這篇文章build an image gallery using redux saga,覺(jué)得寫(xiě)的不錯(cuò),長(zhǎng)短也適...
    smartphp閱讀 6,329評(píng)論 1 29
  • http://gaearon.github.io/redux/index.html ,文檔在 http://rac...
    jacobbubu閱讀 80,410評(píng)論 35 198
  • 《東京女子鑒圖》女主人公綾從小有一個(gè)夢(mèng)想:她想成為一個(gè)令人羨慕的人。主要講述了她從自己出生的小城市來(lái)到了大都市東京...
    依心y閱讀 489評(píng)論 0 0
  • 看了電影,“激動(dòng)得不行”,找了電子書(shū)補(bǔ)充一下被刪減的情節(jié),神他媽愛(ài)情! 主人公阿里薩文藝青年,用情專一,然而家庭出...
    扁蟲(chóng)魚(yú)閱讀 318評(píng)論 0 0

友情鏈接更多精彩內(nèi)容