// React Redux
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import {Provider, connect} from 'react-redux';
function counterUpReducer (state = 0, action) {
switch (action.type) {
case 'COUNTER_UP': return state + action.value;
default: return state;
}
}
function counterUpAction (value) {
return {
type: 'COUNTER_UP'
, value: value
};
}
function counterDownReducer (state = 0, action) {
switch (action.type) {
case 'COUNTER_DOWN': return state + action.value;
default: return state;
}
}
function counterDownAction (value) {
return {
type: 'COUNTER_DOWN'
, value: value
};
}
const reducers = combineReducers({
counterUp: counterUpReducer
, counterDown: counterDownReducer
});
const initialState = {
counterUp: 0
, counterDown: 0
};
const store = createStore(reducers, initialState, applyMiddleware(logger(), thunk));
store.subscribe(() => {console.log(store.getState());});
class App extends Component {
render () {
return (
<CounterBlock />
);
}
}
class CounterBlock extends Component {
render () {
return (
<Counter />
);
}
}
class Counter extends Component {
constructor (props) {
super(props);
this.state = store.getState();
}
render () {
return (
<div id="counter">
<span id="counter-up">{this.props.counterUp}</span>
{' '}
<span id="up" onClick={this.props.handleUpClick.bind(this)}>Вверх</span>
<br /><br />
<span id="counter-down">{this.props.counterDown}</span>
{' '}
<span id="down" onClick={this.props.handleDownClick.bind(this)}>Вниз</span>
</div>
);
}
}
function mapStateToProps (state) {console.log(state.counterUp);
return {
counterUp: state.counterUp
, counterDown: state.counterDown
};
}
function mapDispatchToProps (dispatch) {
return {
handleUpClick: function () {
dispatch(counterUpAction(1));
this.setState(Object.assign({}, this.state, {counterUp: store.getState().counterUp}));
}
, handleDownClick: function () {
dispatch(counterDownAction(-1));
this.setState(Object.assign({}, this.state, {counterDown: store.getState().counterDown}));
}
};
}
Counter = connect(mapStateToProps, mapDispatchToProps)(Counter);
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
Комментариев нет:
Отправить комментарий