2018-10-15 10:26:38   Visit  1543

combineReducers 主要用来合并零碎的reducer

定义reducer

const initialState = {
    text: \\\"Map 1\\\"
};

/*
   对应不同 action.type 的处理函数,需要返回一个新的 state
   也可以 switch 语句 处理不同 action.type
*/
const typesCommands = {
    [\\\"CHANGE_TEXT\\\"](state, action) {
        console.log(action)
        var v = Object.assign({}, state, {
            text: action.text
        });
        console.log(v);
        return v;
    } 
} 
export default function reducer(state = initialState, action) { 
    const actionResponse = typesCommands[action.type]; 
    let v = actionResponse ? actionResponse(state, action) : state ;
    return v;
}

使用combineReducers

import { combineReducers } from \\\'redux\\\';
import { routerReducer } from \\\'react-router-redux\\\';
 import mapreducer from \\\'./map\\\'


const Reducers = {
    mapreducer
} 
export default combineReducers(Reducers); 

组件代码改动

import React from \"react\";
import { connect } from \'react-redux\';  
class Map extends React.Component {
    render() {
        const { handleChange } = this.props;
        return (
            <div className=\"fullContent\" style={{ backgroundColor: \"red\" }}>
                Type something:
                <input onChange={handleChange}
                    value={this.props.text} />{this.props.text}
            </div>
        );
    }
}

 

const handleChangeAction = {
    type: \'CHANGE_TEXT\'
}
const MapAction = { type: \'mapinput\' }
export default connect(
    state => ({ text: state.mapreducer.text }),
    dispatch => ({
        handleChange: (e, a, b) => {
            let text = e.target.value;
            dispatch({
                type: \'CHANGE_TEXT\', text: text
            })
        },
    })
)(Map);

属性存储在state.mapreducer中

©2017 Leechg.com