redux的作用
react 本身是通过props传递state的,层级嵌套太深的话,传递属性就需要一层层向下传递,回传也需要一层层的回调。
redux 的作用就是实现跨级传递state
react-redux 是连接react && redux的插件
简单例子
实现数字增加和减少
app.js
//app.js
import React from ‘react’
import ReactDOM from 'react-dom’
import {Provider} from 'react-redux’
import Action from './Action’
import store from './Reducers’
ReactDOM.render(<Provider store={store}><Action/></Provider>, document.getElementById('root’));
Reducers.js
//Reducers.js
import {createStore} from “redux”;
let reducers = function(state=1, action){
switch (action.type) {
case ‘ADD’:
return state + 1;
break;
case ‘DEC’:
return state - 1;
break;
default:
return state;
}
};
export default createStore(reducers);
Action.js
//Action.js
import {connect} from 'react-redux’
class Action extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<h1>current number: {this.props.state}</h1>
<button onClick={this.props.dec}>dec</button>
<button onClick={this.props.add}>add</button>
</div>
);
}
}
function mapStateToProps(state) {
return {
state:state
}
}
function mapDispatchToProps(dispatch) {
return {
add:function(e){
const action = {
type: ‘ADD’,
};
dispatch(action);
},
dec:function(){
const action = {
type: ‘DEC’
};
dispatch(action);
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Action);