react-redux的使用方法我就不提了,那么多教程,都是单个reducer,所以基本从来没人提到一个事情--

先看如下代码:

import React from 'react';
import ReactDOM from 'react-dom';
import {bindActionCreators, combineReducers, createStore} from 'redux';
import {connect, Provider} from 'react-redux';

let initialState = {
    name : 'SpringHack'
};

let reducer_a = (state = initialState, action) => {
    switch (action.type)
    {
        case 'CHANGE_NAME_A':
            return {
                name : 'AAAA'
            }
        break;
        default:
            return state;
        break;
    }
}

let reducer_b = (state = initialState, action) => {
    switch (action.type)
    {
        case 'CHANGE_NAME_B':
            return {
                name : 'BBBB'
            }
        break;
        default:
            return state;
        break;
    }
}

let reducers = combineReducers({
    reducer_a,
    reducer_b
});

let store = createStore(reducers);

let actions = bindActionCreators({
    A() {
        return {
            type : 'CHANGE_NAME_A'
        };
    },
    B() {
        return {
            type : 'CHANGE_NAME_B'
        };
    }
}, store.dispatch);

class App extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div onClick={this.Click.bind(this)}>
                {this.props.reducer_a.name}<br />
                {this.props.reducer_b.name}<br />
            </div>
        );
    }
    Click() {
        actions.A();
        actions.B();
    }
}

const MyApp = connect(state => state)(App);

ReactDOM.render(
    <Provider store={store}>
        <MyApp />
    </Provider>
    , document.body);

看到 Render方法里调用的是

this.props.reducer_a.name

而不是

this.props.name

是因为

combineReducers

方法被调用后所有的 reducer 返回的state有了各自独立的 part--

为毛从来没有一篇教程提到过 2333

还是得看看官方文档,官方Demo是酱紫,没有 combineReducers 的实例:

function todoApp(state = {}, action) {
  return {
    visibilityFilter: visibilityFilter(state.visibilityFilter, action),
    todos: todos(state.todos, action)
  }
}

这已经更改了返回的 state ,和 reducer 是绑定了的。不过,官方没明确说明这一点,但是看下面,改成用 combineReducers 之后:

import { combineReducers } from 'redux'

const todoApp = combineReducers({
  visibilityFilter,
  todos
})

export default function todoApp(state = {}, action) {
  return {
    visibilityFilter: visibilityFilter(state.visibilityFilter, action),
    todos: todos(state.todos, action)
  }
}

官方说“  The state parameter is different for every reducer, and corresponds to the part of the state it manages.  ”,包含了格式变化的问题,详细链接: http://redux.js.org/docs/basics/Reducers.html  

所以,以后还是看官方文档吧,而且要仔细,我现在连翻译的文档都不怎么敢信了,当然公认的大神还是信得过的--