React之Redux基本使用

一.Redux中的单想数据流行

  _________               ____________               ___________
                |         |             |            |             |           |
                | Action  |------------▶| Dispatcher |------------▶| callbacks |
                |_________|             |____________|             |___________|
                     ▲                                                   |
                     |                                                   |
                     |                                                   |
 _________       ____|_____                                          ____▼____
|         |◀----|  Action  |                                        |         |
| Web API |     | Creators |                                        |  Store  |
|_________|----▶|__________|                                        |_________|
                     ▲                                                   |
                     |                                                   |
                 ____|________           ____________                ____▼____
                |   User       |         |   React   |              | Change  |
                | interactions |◀--------|   Views   |◀-------------| events  |
                |______________|         |___________|              |_________|

二.创建Reducer处理函数,该Reducer作用便是监听action做出相应的对state的处理

var userReducer = function (state={}, action) {
    console.log('userReducer was called with state', state, 'and action', action)

    switch (action.type) {
        case 'SET_NAME':
            return {
                ...state,
                name: action.name
            }
        default:
            return state;
    }
}
var itemsReducer = function (state = [], action) {
    console.log('itemsReducer was called with state', state, 'and action', action)

    switch (action.type) {
        case 'ADD_ITEM':
            return [
                ...state,
                action.item
            ]
        default:
            return state;
    }
}

三.用combineReducers合并Reducer,并通过createStore绑定给Redux生成store

store可以通过getState()返回一个state对象

import { createStore, combineReducers } from 'redux'

var reducer = combineReducers({
    user: userReducer,
    items: itemsReducer
})
var store_0 = createStore(reducer)


console.log("\n", '### It starts here')
console.log('store_0 state after initialization:', store_0.getState())
输出:
// store_0 state after initialization: { user: {}, items: [] }

四.通过dispatch派送一个action对象,如果该action在Redux中无法相应,便返回原state

store_0.dispatch({
    type: 'AN_ACTION'
})
console.log('store_0 state after action AN_ACTION:', store_0.getState())
// 输出:store_0 state after action AN_ACTION: { user: {}, items: [] }

五.如果dispatch的action可以在Redux中得到正确的相应,便会得到一个改变后的state

var setNameActionCreator = function (name) {
    return {
        type: 'SET_NAME',
        name: name
    }
}

store_0.dispatch(setNameActionCreator('bob'))
console.log('store_0 state after action SET_NAME:', store_0.getState())
// 输出:
// store_0 state after action SET_NAME: { user: { name: 'bob' }, items: [] }

六.利用Redux的中间件api实现Reducer处理异步action

1.0  如上所述,中间件由三个嵌套的函数构成(会依次调用):

1) 第一层向其余两层提供分发函数和 getState 函数

(因为你的中间件或 action creator 可能需要从 state 中读取数据)

2) 第二层提供 next 函数,它允许你显式的将处理过的输入传递给下一个中间件或 Redux

(这样 Redux 才能调用所有 reducer)。

3) 第三层提供从上一个中间件或从 dispatch 传递来的 action,

这个 action 可以调用下一个中间件(让 action 继续流动) 或者

以想要的方式处理 action。

var thunkMiddleware = function ({ dispatch, getState }) {
    // console.log('Enter thunkMiddleware');
    return function(next) {
        // console.log('Function "next" provided:', next);
        return function (action) {
            // console.log('Handling action:', action);
            return typeof action === 'function' ?
                action(dispatch, getState) :
                next(action)
        }
    }
}

2.0为了让 Redux 知道我们有一个或多个中间件,我们使用 Redux 的

辅助函数:applyMiddleware.

applyMiddleware 接收所有中间件作为参数,返回一个供 Redux createStore 调用的函数。

当最后这个函数被调用时,它会产生一个 Store 增强器,用来将所有中间件应用到 Store 的 dispatch 上。

import { createStore, combineReducers, applyMiddleware } from 'redux'

const finalCreateStore = applyMiddleware(thunkMiddleware)(createStore)
// 针对多个中间件, 使用:applyMiddleware(middleware1, middleware2, ...)(createStore)

var reducer = combineReducers({
    speaker: function (state = {}, action) {
        console.log('speaker was called with state', state, 'and action', action)

        switch (action.type) {
            case 'SAY':
                return {
                    ...state,
                    message: action.message
                }
            default:
                return state
        }
    }
})

const store_0 = finalCreateStore(reducer)

3.0 在增强Redux的store之后,因为已经添加了middleware中间件来做中间人处理异步操作,现在Redux可以监听异步action了

var asyncSayActionCreator_1 = function (message) {
    return function (dispatch) {
        setTimeout(function () {
            console.log(new Date(), 'Dispatch action now:')
            dispatch({
                type: 'SAY',
                message
            })
        }, 2000)
    }
}

console.log("\n", new Date(), 'Running our async action creator:', "\n")

store_0.dispatch(asyncSayActionCreator_1('Hi'))
//当我们调用异步 action creator 两秒之后,action 成功被分发出去。

七.Redux中的订阅state信息

store.subscribe(function() {
        // retrieve latest store state here
        // Ex:
        console.log(store.getState());
    })

 

 

转载于:https://my.oschina.net/u/3937325/blog/1934135

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值