看阮一峰大神的redux入门教程,跟着写了一个加减数字功能的小例子,记录一下逻辑分析
reduce文件夹下的index.js
定义个名为counter的reducer,本质是一个纯函数,传入state,action两个参数返回一个新的state
export default function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
components文件夹下的counter.js,定义了Counter组件
import React, {
Component
} from 'react';
import PropTypes from 'prop-types';
class Counter extends Component {
constructor(props) {
super(props);
this.incrementIfOdd = this.incrementIfOdd.bind(this);//初始化绑定inrementIfOdd方法
this.incrementAsync = this.incrementAsync.bind(this);//初始化绑定incrementAsync方法
}
//定义incrementIfOdd方法,如果value属性值不为偶数,就执行属性中的onIncrement方法
incrementIfOdd() {
if (this.props.value % 2 !== 0) {
this.props.onIncrement();
}
}
//定义incrementAsync方法,延迟一秒执行属性中的onIncrement方法
incrementAsync() {
setTimeout(this.props.onIncrement, 1000);
}
render() {
//解构赋值,获取属性中的value、onIncrement、onDecrement值
const {
value,
onIncrement,
onDecrement
} = this.props;
return (
<p>
Clicked:{value} times
{' '}
<button onClick = {onIncrement}> + </button>
{' '}
<button onClick = {onDecrement}> - </button>
{' '}
<button onClick = {this.incrementIfOdd}> Increment if odd</button>
{' '}
<button onClick = {this.incrementAsync}> Increment Async</button>
</p>
)
}
}
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired
}
export default Counter;
src文件夹下的index.js,
import React from 'react';
import ReactDom from 'react-dom';
import {
createStore
} from 'redux';
import Counter from './components/counter.js';
import counter from './reducer/index.js';
const store = createStore(counter);//以counter为参数创建store
const rootEl = document.getElementById('root');
const render = function() {
ReactDom.render(
<Counter value = {store.getState() }
onIncrement = {function(){store.dispatch({type:'INCREMENT'})} }
onDecrement = {function(){store.dispatch({type:'DECREMENT'})} }
/>,
rootEl
)
}
render();
store.subscribe(render);
用户发出action,使用组件属性中的onIncrement方法处理,里面包含了store.dispatch(action);
store.getState()方法获取当前状态state的值
store.subscribe()方法监听state是否变化,变化后调用监听函数
效果如下
参考资料:http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html