React搭建-Redux

react-redux是基于Flux理论的一个组件 http://redux.js.org/docs/basics/UsageWithReact.html

一般redux包含几个模块:reducers, action, middlewares
React搭建-Redux
 

同样的,在redux下面会有一个index.js文件,主要是为了集合reducers和middleware生成项目用的store对象:

import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers';
import middlewares from './middlewares';

let store = window.store = createStore(
              reducers,
              applyMiddleware(...middlewares)
            );

export default store;

 在这里,同时给window.store赋值,主要是为了应付特殊情况,不过现在还没有遇到过

在middlewares中,是加入的一些辅助性的方法,比如logger, 比如像redux simple router这样的组件,同样的为了便于管理,在middlewares的文件夹下面有一个index.js文件,用来整合所有的组件

index.js

import logger from './logger';
import thunk from 'redux-thunk';
import simpleRouter from './simpleRouter';

const middlewares = [ logger, thunk, simpleRouter ];

export default middlewares;

logger.js

import logger from './logger';
import thunk from 'redux-thunk';
import simpleRouter from './simpleRouter';

const middlewares = [ logger, thunk, simpleRouter ];

export default middlewares;

simpleRouter.js

import logger from './logger';
import thunk from 'redux-thunk';
import simpleRouter from './simpleRouter';

const middlewares = [ logger, thunk, simpleRouter ];

export default middlewares;

对于redux,最主要的还是actions和reducers

actions是用来发送状态给redux的,下面有一个index.js文件,也可以根据需求建立其他的js文件,然后在index.js里面引入

index.js

import { HELLO_WORLD } from '../types';

export function sayHello(message) {
  return {
    type: HELLO_WORLD,
    message
  };
}

reducers是用来获取action的状态,修改对应的state。在index.js中,一般是用来combineReducers,然后返回集合过的reducers

index.js:

import { combineReducers } from 'redux'
import { routeReducer } from 'redux-simple-router';

import entities from './entities';

const reducers = combineReducers({
	entities,
	routing: routeReducer
});

export default reducers;

entities.js:

import { HELLO_WORLD } from '../types';

export default function entities(state = {
  helloWorld: "hello World"
}, action) {
  switch(action.type) {
    case HELLO_WORLD:
      return {
        ...state,
        helloWorld : action.message
      };
    default:
      return state;
  }
}

看了上面的代码都能看到里面引入了types,为了便于管理,我喜欢把types分开列到一个文件中,由于分开到多个文件,感觉在action和reducers中引入比较麻烦,所以决定放在一个index.js文件中,用分割线隔开不同种类的type:

index.js

/**------------------------- Entities -------------------------**/
export const HELLO_WORLD = 'HELLO_WORLD';

相关推荐