当前位置: 移动技术网 > IT编程>网页制作>CSS > 案例:React+Redux使用异步Action实现加减

案例:React+Redux使用异步Action实现加减

2018年11月03日  | 移动技术网IT编程  | 我要评论

案例:react+redux使用异步action实现加减

其实很早就已经接触react了,当时还看的是es5语法,本来js基础就不扎实,秉着初生牛犊不怕虎的精神去看了react,结果看了云里雾里,这种硬塞的知识过几天就全忘了,过了一段时间,想着有空了,就又去看了react,这次直接看的es6语法,看完后顺道看了react-redux,刚开始,很痛苦,本来react就已经不太容易理解了,再加上redux和react-redux,更加懵逼了,一个很简单的应用还要分成action、reducer、ui、container组件,然后分别串联工作,就感觉脑袋要炸了,但是跟着阮大神写了第一个demo。

先看文件目录,我没有想demo里那样全写在一个文件里,分类可以帮助更好的理解。

1.加减计数器:先定义用户有两种操作,一种是加,一种是减,也就是action有两种。

export const increaseaction = {

type: 'increase'

}

export const decreaseaction = {

type: 'decrease'

}

注意,action的type是必须的,明文规定必须要。

2.然后是reducer,reducer是收到action,然后计算得出新的state,以便让ui组件渲染新的状态,因为每个state对应不同的view。

const setcounter = (state = {count: 0}, action) => {

switch (action.type) {

case 'increase':

return {count: state.count + 1};

case 'decrease':

return {count: state.count - 1}

default:

return state;

}

}

export default setcounter;

reducer对action的加减操作都进行了判断处理,然后返回新的state。

3.然后是ui组件,就是view部分。

import react, {proptypes} from 'react';

class counter extends react.component {

render() {

const {value, onincreaseclick,ondecreaseclick} = this.props,

btnstyle = {

width: '110px',

height: '30px',

color: '#fff',

backgroundcolor: 'green',

border: '1px solid green',

borderradius: '5px',

cursor: 'pointer'

},

textstyle = {

fontsize: '20px'

};

return (

{value}

increasedecrease

) } } counter.proptypes = { value : proptypes.number.isrequired, onincreaseclick: proptypes.func.isrequired, ondecreaseclick: proptypes.func.isrequired } export default counter;

这里ui组件接收了来自父组件的props,onincreaseclick,ondecreaseclick是两个按钮事件,用户点击触发事件然后传递action,到container接收action。

4.container接收action,通过dispatch将action传递给store。

import {connect} from 'react-redux';

import counter from '../components/counter';

import {increaseaction, decreaseaction} from '../action/index';

const mapstatetoprops = (state) => ({

value: state.count

})

const mapdispatchtoprops = (dispatch) => ({

onincreaseclick: () => dispatch(increaseaction),

ondecreaseclick: () => dispatch(decreaseaction)

})

const app = connect(

mapstatetoprops,

mapdispatchtoprops

)(counter)

export default app;

这里调用了react-redux的connect方法,用于将ui组件生成容器组件,其实就是将两者connect连接在一起,connect需要接受两个参数,mapstatetoprops和mapdispatchtoprops。

mapstatetoprops方法是讲state转成props传给ui组件,mapdispatchtoprops是ui组件参数到store.dispatch的映射,就是接收ui组件传入的action,最后的counter就是ui组件。

5.最后是store的生成场所。

import react from 'react';

import reactdom from 'react-dom';

import {provider} from 'react-redux'

import {createstore} from 'redux';

import reducer from './reducer/index';

import app from './container/app';

const store = createstore(reducer);

reactdom.render(

,

document.getelementbyid('app')

);

这边createstore(reducer)将reducer传入,这样在action通过dispatch传入store的时候会通过reducer处理action,从而生成相应的新的state,再让ui组件重新渲染。

以上就是我第一个小demo,记录我学习的脚步,有问题欢迎dalao们指出,请多关照

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网