react redux combine

store:

import {createStore,applyMiddleware, compose} from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers/rootReducer";

const middlewares = [
    applyMiddleware(thunk)
];
const store = initialState => createStore(rootReducer, initialState, compose(...middlewares));

export default store;

rootReducer:

import {combineReducers} from "redux";
import {reducer as toastr} from "react-redux-toastr";

const rootReducer = combineReducers({
    toastr,
    counterReducer
});

export default rootReducer;

counterReducer:

import * as types from "../actions/actionType";

const initialState = {
   count: 0
};

const counterReducer = function (state = initialState, action) {
    const count = state.product;
    switch (action.type) {
        case types.INCREMENT:
            return {count: count + 1};
        case types.DECREMENT:
            return {count: count - 1};
        default:
            return state;
            
    }
    
};

export default counterReducer;

actionType:

export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

Counter:

import {connect} from "react-redux";
import * as types from "actions/actionType";

const mapStatetoProps = state =>{
    return {
        value: state.counterReducer.count
    }
}
const mapDispatchToProps =dispatch => {
    return {
        onIncrement: ()=>dispatch({type: types.INCREMENT}),
        onDecrement: ()=>dispatch({type: types.DECREMENT})
    }
}

class Counter extends React.Component {
    render() {
        const {count, onIncrement, onDecrement} = this.props;
        return (
            <div>
                <span>{count}</span>
                <button onClick={onIncrement}>+</button>
                <button onClick={onDecrement}>-</button>
            </div>
        )
    }
}
const CounterContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(Counter)
export default CounterContainer;

猜你喜欢

转载自www.cnblogs.com/Nyan-Workflow-FC/p/8855757.html