js-redux学习笔记

1、action creator 就是函数,负责构建一个 action (是的,action creator 这个名字已经很明显了)并返回它。

var actionCreator = function() {
    return {
        type: 'AN_ACTION'
    }
}

type 决定如何处理 action。当然,action 依旧可以拥有其他属性,你可以任意存放想要的数据

2、在实际的场景中,我们需要的是将 action 发送到某个地方,让关心它的人知道发生了什么,并且做出相应的处理。

我们将这个过程称之为“分发 action(Dispatching an action)”。

3、我们把 Redux 实例称为 store 并用以下方式创建:

import { createStore } from 'redux'
var store = createStore(reducer)

在被调用时,一个 reducer 会得到这些参数:(state, action)

在应用初始化时,state 还没被初始化,因此它的值是 "undefined"。

4、在 reducer 里用 switch 来响应对应的 action 。用 switch 的时候, **永远** 不要忘记放个 “default” 来返回 “state”,否则,你的 reducer 可能会返回 “undefined” (等于你的 state 就丢了)。

5、定义 2 个 reducer:

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

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

    switch (action.type) {
        // etc.
        default:
            return state;
    }
}

使用多个 reducer 创建一个 Redux 实例:

import { createStore, combineReducers } from 'redux'

var reducer = combineReducers({
    user: userReducer,
    items: itemsReducer
})
var store_0 = createStore(reducer)
console.log('store_0 state after initialization:', store_0.getState())
// 输出:
// store_0 state after initialization: { user: {}, items: [] }

由于我们为每个 reducer 初始化了一个特殊的值(userReducer 的是空对象 {} ,itemsReducer 的是空数组 [] ),所以在最终 Redux 的 state 中找到那些值并不是巧合。

6、dispatch-action待续

原文地址:https://www.cnblogs.com/zczhangcui/p/6680320.html