Source code Github location:
https://github.com/howareyoucolin/React-Redux-Counter
Reducer
const initialState = {
count: 10
};
function rootReducer(state = initialState, action) {
if(action.type == 'INCREASE_COUNT'){
return {
...state,
count: (state.count + 1) > 20 ? 20 : state.count + 1
}
}
else if(action.type == 'DECREASE_COUNT'){
return {
...state,
count: (state.count - 1) < 0 ? 0 : state.count - 1
}
}
return state;
};
export default rootReducer;
mapStateToProps 例子:
import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
//Import scss
import './scss/screen.scss';
//Component A
class Screen extends React.Component {
render() {
return (
<div className="screen">
{ this.props.count }
</div>
)
}
};
const mapStateToProps = (state) => {
return { count: state.count };
};
export default connect(mapStateToProps)(Screen);
mapDispatchToProps 例子:
import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
//Import scss
import './scss/btn.scss';
//Component A
class Btn extends React.Component {
clickHandler = () => {
if(this.props.sign == '+') this.props.increment();
if(this.props.sign == '-') this.props.decrement();
}
render() {
return (
<div className="btnWrap">
<button onClick={this.clickHandler}> {this.props.children} </button>
</div>
)
}
};
const mapDispatchToProps = (dispatch) => {
return {
increment:() => {
dispatch({type:'INCREASE_COUNT'});
},
decrement:() => {
dispatch({type:'DECREASE_COUNT'});
}
}
}
export default connect(null,mapDispatchToProps)(Btn);
Counter 作用展示:
由369usa学生陈小弟所编写.




