React-ReduxReduxActionfunction addTodo(text) { return { type: ADD_TODO, text }}type 属性是必须的。Reducerfunction todoApp(state = initialState, action) { switch (action.type) { case ADD_TODO: return Object.assign({}, state, { todo: action.todo }) default: return state }}1、需要一个case与action的type一致。2、必须在switch的defautl返回原state。Store管理整个应用的 state提供getState()方法,可以获取state通过dispatch(action)设置state提供subscribe(listener)注册和取消注册监听事件React-Redux是Redux的React实现,可参考 Official React bindings for Redux.安装yarn add redux react-redux//ornpm i redux react-redxu组件层级划分表现性组件只负责显示UI的组件。例如:<div></div>容器性组件不处理UI的组件,也不处理数据,只为UI组件提供数据的组件。例如:connect(state => state)(<YourComponent />)其他组件除以上两种组件以外的组件。使用Redux我们以一个计数器的例子来说明如何使用React-redux.设计表现性组件需要:显示当前计数,默认为0;累加按钮,每次单击加1;递减按钮,每次单击减1;重置按钮,单击将计数设置为0。import React from ‘react’;export default ({counter = 0}) => { const styles = { display: ‘flex’, justifyContent: ‘space-around’ }; return ( <div> <h1>当前计数为:{counter}</h1> <div style={styles}> <button>加</button> <button>减</button> <button>重置</button> </div> </div> );};设置容器性组件目的是将表现性组件中的数据抽离出去交给redux管理,然后通过容器性组件将redxu与表现性组件关联起来。import { connect } from ‘react-redux’;import CounterIndex from ‘../components/chapter03/Counter’;export default connect(state => ({ …state.counterRedux }))(({ counter, dispatch }) => <CounterIndex counter={counter} dispatch={dispatch} />);Actionexport const COUNTER_ACTION = ‘COUNTER_ACTION’;export const addActioner = ({counter}) => { return {type: COUNTER_ACTION, counter: counter + 1};};export const subActioner = ({counter}) => { return {type: COUNTER_ACTION, counter: counter - 1};};export const resetActioner = () => { return {type: COUNTER_ACTION, counter: 0};};Reducerimport { COUNTER_ACTION } from ‘../actions/CounterAction’;export default (state, action) => { switch (action.type) { case COUNTER_ACTION: return { …state, counter: action.counter }; default: return state; }}Storeimport React from ‘react’;import { Provider } from ‘react-redux’;import { createStore } from ‘redux’;import CounterReducer from ‘../reducers/CounterReducer’;let store = createStore(CounterReducer);export default ({ children }) => <Provider store={store}>{children}</Provider>Redux 调试插件console日志安装redux-logger组件:yarn add redux-logger –dev。然后加入到redux store中即可:import { createLogger } from ‘redux-logger’;store = createStore(reducers, createLogger());例如:redux扩展程序需要在Chrome应用市场安装Redux DevTools.然后在store中使用增强功能将redux-logger加入即可:const logger = window.REDUX_DEVTOOLS_EXTENSION_COMPOSE(createLogger());store = createStore(reducers, logger);在线实例推荐阅读《React 手稿》