Redux(一)

131 阅读1分钟

Redux概念

Redux is a predictable state container for JavaScript apps.

简言之,Redux就是用于管理数据状态的JavaScript应用工具,且随着SPA开发的日益复杂,Redux有效降低了state的管理难度。此外,Redux支持React、Angular、jQuery及纯JavaScript。

多个组件依赖或影响同一个状态时,使用react进行状态提升(将组件之间共享的状态交给组件最近的公共父节点管理),将会使得代码的组织管理维护极为苦难,Redux为此提供了很好的解决方案。


Redux工作流程

Redux基本运作流程

结合React


store

Redux工作流程中的store为所有数据提供管理,在开发时,优先编写store。

    import {createStore} from 'redux';
    const store = cresteStore(reducer);
    export default store;

reducer

reducer为store提供管理能力。(reducer只能接收state,不能改变state)

    const defaultState = {};
    //state为整个项目中需要管理的数据
    export default (state=defaultState,action)=>{
        return state;
    }

组件获取store中的数据

store.getState()获取

    import store from './store';
    class App extends React.Component{
        constructor(props){
            super(props);
            console.log(store.getState());
        }
    }

使用

    this.state = store.getState();

Redux Dev Tools

在浏览器中安装插件,在store.js中进行配置:

    const store = createStore(reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    );

Action

通过Action改变redux中state的值。Action就是一个对象,有两个属性,第一个为对Action的描述,第二个为要更新的值。

dispatch

action创建后,需要通过dispatch()派发给store:

    const action = {
        type:'change_value',
        value:e.target.value
    };
    store.dispatch(action);

actionType

为便于管理action的type,将action的type抽取出来,声明成常量。

actionCreator

创建actionCreator,统一管理action的声明。