学知识不写demo就是耍流氓
1.先讲一下Redux在没有Middleware中间件时,数据流是这样的:
React component调用Action Creator让它创建并返回action,然后把这个action抛给reducers,reducers 处理actions,计算并返回new state,state一旦发生改变,就会触发React component重新渲染页面
redux2.React+Redux实现simple counter小demo
效果图:
点击Increase按钮数字+1,点击Decrease按钮数字-1
实现的逻辑
看看simple counter代码
1)定义reducerpublic/src/reducers/handle-counter.js
,reducer包含两个参数current state
和action
. state初始化为{count:0}
,因demo中有Increase和 Decrease操作,所以要有两个action ---COUNTER_INCRE
和COUtNTER_DECRE
const INITIAL_STATE = {
count:0
}
const handleCounter = (state =INITIAL_STATE , action)=> {
switch(action.type){
case 'COUNTER_INCRE':
return Object.assign({}, state, { count: state.count + 1});
case 'COUNTER_DECRE':
return Object.assign({}, state, { count: state.count -1});
}
return state;
};
export default handleCounter;
2)创建store,store中存放的是reducer 函数和state.因为我们只有一个reducer函数---handleCounter,所以直接引入就行
import {createStore} from 'redux';
import handleCounter from './reducers/handle-counter';
let store = createStore(handleCounter);
3)创建Counter组件
import React, {Component} from 'react';
class Counter extends Component {
//加1事件
onIncrement() {
this.props.Increase();
}
//减1事件
onDecrement() {
this.props.Decrease();
}
render() {
return (
<div>
<h2>Counter</h2>
<p>The counter value is {this.props.count}</p>
<button onClick={this.onIncrement.bind(this)}>Increase</button>
<button onClick={this.onDecrement.bind(this)}>Decrease</button>
</div>
)
}
}
4)然后为Counter.js connect store,以至于能获取到store 里的state,还能修改state. 我们看到connect我们传state和dispatch进去,mapStateToProps 和 mapDisaptchToProps 分别将传来的state及dispatch映射成props,通过connect方法绑定组件Counter,Counter就可以获取到props值
const mapStateToProps = function (state) {
return state;
};
const mapDispatchToProps = function (dispatch) {
return {
Increase: function () {
return dispatch({type: "COUNTER_INCRE"})
},
Decrease: function () {
return dispatch({type: "COUNTER_DECRE"})
}
}
};
const CounterPackage = connect(mapStateToProps, mapDispatchToProps)(Counter);
5)在main.js中给Couter组件提供先前创建好的store
import ReactDom from 'react-dom';
import {Provider} from 'react-redux';
import Counter from './components/Counter';
ReactDom.render(
<Provider store = {store}>
<Counter />
</Provider>,
document.getElementById('app')
);
好了,一个React+Redux的simple counter就完成了
demo地址
参考文章
https://codepen.io/anuragasaurus/post/react-basics-simple-counter-made-with-react-and-redux
每天都努力一点点
谢谢你看完
网友评论