react组件案例--基于redux的计数器

责编:menVScode 2017-06-23 0:54 阅读(998)

首先,来看看案例的目录结构

QQ截图20170623004128

文件的位置 index.js


import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './components/Counter';
import {createStore} from 'redux';
import reducer from './reducers/index';
//console.log(reducer)
//createStore接受一个函数,这个函数就是reducer let store = createStore(reducer); //console.log(store) //console.log(store.getState()) const render = () =>{ ReactDOM.render( <Counter value={store.getState()} onAdd={()=>store.dispatch({type:'ADD'})} onDel={()=>store.dispatch({type:'DEL'})} />, document.getElementById('app') ); } render(); store.subscribe(render);

文件的位置 reducers > index.js

export default (state=0,action)=>{
	switch(action.type){
		case 'ADD':
			return state+1
		case 'DEL':
			return state-1
		default:
			return state
	}
}

文件的位置 components > index.js

import React from 'react';
class Counter extends React.Component{
	changeEven=()=>{
		if (this.props.value%2!=0) {
			this.props.onAdd()
		}
	}
	delay=()=>{
		var _this=this;
		setTimeout(function(){
			_this.props.onAdd()
		},1000);
	}
	render(){
		//console.log(this.props.onAdd);
		//console.log(this.props);
		let {value,onAdd,onDel} = this.props;
		return(
			<div>
				点击 {value} 次&nbsp;
				<button onClick={onAdd} >+</button>&nbsp;
				<button onClick={onDel} >-</button>&nbsp;
				<button onClick={this.changeEven}>奇数变偶数</button>&nbsp;
				<button onClick={this.delay}>延时加1</button>
			</div>
		)
	}
}
export default Counter;

        如果对此这篇文章不好理解的话,那建议先看看这篇文章《react组件案例--计数器》-- http://menvscode.com/detail/59494e8f6f402968fec7cd91,是运用普通方法写的。

前端交流群: MVC前端网(menvscode.com)-qq交流群:551903636

邮箱快速注册

忘记密码