继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Redux入门

holdtom
关注TA
已关注
手记 1703
粉丝 240
获赞 991


Redux是什么?

一个状态(State)管理器,集中管理应用中所有组件的状态。

所有组件的状态保存在一个对象里。

虽然Redux与React没有任何直接关系,但是Redux的主要用途(几乎是唯一用途)是为React服务,用于组件的状态管理,简化复杂应用下组件状态的调用关系。

Redux主要用途?

1)提供一个状态集中管理的容器。

2)简化组件依赖关系,使可以共享或改变所有组件的状态。解决Redux更改子组件状态层层调用的繁琐。

3)状态的改变,会引起视图的改变,所以如果想改变视图(View),不管涉及谁的改变,统一找Redux就行了,因为状态都在他那里集中管理。

4)Redux 规定, 一个 State 对应一个 View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么样,反之亦然。

如何使用?

1)创建唯一的一个store:

    import { createStore } from 'redux';

    //reducer在后面解释,createStore需要传入reducer或reducer集合。

    const reducer = function(state, action) {

            return state;

    }

    const store = createStore(reducer);

2)获取state

    const state = store.getState();

3)改变state,需要发送action通知。

尽管Redux可以通过setState改变组件状态,但是在redux中只能用dispatch来发送action改变状态。

action 就是 任何人 发出的通知,表示 State 应该要发生变化了。

发送通知的方法是store.dispatch(action)。如下:

    import { createStore } from 'redux';

    const store = createStore(fn);

    store.dispatch({

        type: 'ADD_TODO',

        payload: 'Learn Redux'

    });

Actiond的结构:

    const action = {

        type: 'ADD_TODO',

        payload: 'Learn Redux'

    };

type是必须的,用于识别一个action,payload是可选的,携带任何要传递的数据。

可以写一些辅助函数来创建action,避免dispatch看着太复杂。

4)Reducer 

Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。

Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。

这个函数,是在store创建是传入的,就是上面创建描述的:const store = createStore(fn),也就是:

        const store = createStore(reducer)

以后每当store.dispatch发送过来一个新的 Action,就会自动调用 Reducer,得到新的 State。

Reducer 函数最重要的特征是,它是一个纯函数。

纯函数是函数式编程的概念,必须遵守以下一些约束。

        不得改写参数

        不能调用系统 I/O 的API

        不能调用Date.now()或者Math.random()等不纯的方法,因为每次会得到不一样的结果

由于 Reducer 是纯函数,就可以保证同样的State,必定得到同样的 View。但也正因为这一点,Reducer 函数里面不能改变 State,必须返回一个全新的对象。

5)store.subscribe()

Store 允许使用store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。

    import { createStore } from 'redux';

    const store = createStore(reducer);

    store.subscribe(listener);

显然,只要把 View 的更新函数(对于 React 项目,就是组件的render方法或setState方法)放入listen,就会实现 View 的自动渲染(这个要看React-Redux)。

store.subscribe方法返回一个函数,调用这个函数就可以解除监听。

        let unsubscribe = store.subscribe(() =>

            console.log(store.getState())

        );

        unsubscribe();

Store 的实现

以上介绍了 Redux 涉及的基本概念,可以发现 Store 提供了三个方法。

    store.getState()

    store.dispatch()

    store.subscribe()

    import { createStore } from 'redux';

    let { subscribe, dispatch, getState } = createStore(reducer);

createStore方法还可以接受第二个参数,表示 State 的最初状态。这通常是服务器给出的。

    let store = createStore(todoApp, window.STATE_FROM_SERVER)

上面代码中,window.STATE_FROM_SERVER就是整个应用的状态初始值。注意,如果提供了这个参数,它会覆盖 Reducer 函数的默认初始值。

下面是createStore方法的一个简单实现,可以了解一下 Store 是怎么生成的。(以下代码仅仅用于理解原理,属于进阶教程)

    const createStore = (reducer) => {

        let state;

        let listeners = [];

        const getState = () => state;

        const dispatch = (action) => {

            state = reducer(state, action);

            listeners.forEach(listener => listener());

        };

        const subscribe = (listener) => {

            listeners.push(listener);

            return () => {

                listeners = listeners.filter(l => l !== listener);

            }

        };

        dispatch({});

        return { getState, dispatch, subscribe };

    };          

Reducer 的拆分

Reducer 函数负责生成 State。由于整个应用只有一个 State 对象,包含所有数据,对于大型应用来说,这个 State 必然十分庞大,导致 Reducer 函数也十分庞大。

请看下面的例子。

            const chatReducer = (state = defaultState, action = {}) => {

                const { type, payload } = action;  //解包

                switch (type) {

                    case ADD_CHAT:

                        return Object.assign({}, state, {

                            chatLog: state.chatLog.concat(payload)

                        });

                    case CHANGE_STATUS:

                        return Object.assign({}, state, {

                            statusMessage: payload

                        });

                    case CHANGE_USERNAME:

                        return Object.assign({}, state, {

                            userName: payload

                        });

                    default: return state;

                }

            };

上面代码中,三种 Action 分别改变 State 的三个属性。

ADD_CHAT:chatLog属性

CHANGE_STATUS:statusMessage属性

CHANGE_USERNAME:userName属性

这三个属性之间没有联系,这提示我们可以把 Reducer 函数拆分。不同的函数负责处理不同属性,最终把它们合并成一个大的 Reducer 即可。

    const chatReducer = (state = defaultState, action = {}) => {

        return {

            chatLog: chatLog(state.chatLog, action),

            statusMessage: statusMessage(state.statusMessage, action),

            userName: userName(state.userName, action)

        }

    };

上面代码中,Reducer 函数被拆成了三个小函数,每一个负责接收对应的state、处理对应的action,返回对应的state。

这样一拆,Reducer 就易读易写多了。而且,这种拆分与 React 应用的结构相吻合:一个 React 根组件由很多子组件构成。这就是说,子组件与子 Reducer 完全可以对应。

Redux 提供了一个combineReducers方法,用于 Reducer 的拆分。你只要定义各个子 Reducer 函数,然后用这个方法,将它们合成一个大的 Reducer。

        import { combineReducers } from 'redux';

        const chatReducer = combineReducers({

            chatLog,

            statusMessage,

            userName

        })

        export default todoApp;

上面的代码通过combineReducers方法将三个子 Reducer 合并成一个大的函数。

这种写法有一个前提,就是 State 的属性名必须与子 Reducer 同名。如果不同名,就要采用下面的写法。

        const reducer = combineReducers({

            a: doSomethingWithA,

            b: processB,

            c: c

        })

        // 等同于

        function reducer(state = {}, action) {

            return {

                a: doSomethingWithA(state.a, action),

                b: processB(state.b, action),

                c: c(state.c, action)

            }

        }

总之,combineReducers()做的就是产生一个整体的 Reducer 函数。该函数根据 State 的 key 去执行相应的子 Reducer,并将返回结果合并成一个大的 State 对象。

下面是combineReducer的简单实现(实现,告诉你原理,所以然)。

        const combineReducers = reducers => {

            return (state = {}, action) => {

                return Object.keys(reducers).reduce(

                    (nextState, key) => {

                        nextState[key] = reducers[key](state[key], action);

                        return nextState;

                    },

                    {} 

                );

            };

        };

你可以把所有子 Reducer 放在一个文件里面,然后统一引入(这句话是干货)。

        import { combineReducers } from 'redux'

        import * as reducers from './reducers'

        const reducer = combineReducers(reducers)

究竟每个reducer如何处理对应的状态,还要参考如下文字才会更清楚:

http://blog.51cto.com/livestreaming/2313439

工作流程

本节对 Redux 的工作流程,做一个梳理。

Redux入门

首先,发出 Action。

Action可以从任何地方发出,触发的原因可能是界面操作、时间、服务器消息等等,一个目的,告诉Store我要改变某种状态。

    store.dispatch(action);

然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。

    let nextState = todoApp(previousState, action);

State 一旦有变化,Store 就会调用监听函数。

// 设置监听函数

store.subscribe(listener);

listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。

    function listerner() {

        let newState = store.getState();

        component.setState(newState);   

    }

实际上React-Redux有更自动化的方法,请参考:

https://daveceddia.com/how-does-redux-work/

Redux如何触发组件view的改变?

这个是React-Redux的内容,需要把组件connect到redux中,如果没有connect,就没有组件view的自动改变。

就像这样:

    function mapStateToProps(state) {

        return {

            count: state.count

        };

    }

    export default connect(mapStateToProps)(MyCompnent);

请参考:

https://daveceddia.com/how-does-redux-work/

Redux VS React-Redux

See, redux gives you a store, and lets you keep state in it, and get state out, and respond when the state changes. But that’s all it does. It’s actually react-redux that lets you connect pieces of the state to React components. That’s right: redux knows nothing about React at all.

请参考:

https://daveceddia.com/how-does-redux-work/

辅助阅读:

https://reactnative.cn/docs/state/

https://segmentfault.com/a/1190000011474522

如果还不清楚,或者想进一步学习React-Redux,建议读如下文档,非常有用:

https://daveceddia.com/what-does-redux-do/

https://daveceddia.com/how-does-redux-work/

©著作权归作者所有:来自51CTO博客作者sendoffice的原创作品,如需转载,请注明出处,否则将追究法律责任


打开App,阅读手记
4人推荐
发表评论
随时随地看视频慕课网APP