通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
# 一个简单的计数器开始 首先为了理清一些概念,先写一个小Demo进行说明。 `index.js` ```js import React, { Component } from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' import { createStore } from 'redux' const reducers = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } }; const store = createStore(reducers) const rootEl = document.getElementById('root') class Counter extends Component{ constructor (props) { super(props); this.increment = this.increment.bind(this); this.decrement = this.decrement.bind(this); } increment () { const { onIncrement } = this.props onIncrement() } decrement () { const { onDecrement } = this.props onDecrement() } render () { const { value } = this.props return ( <p> Count: {value} <br/> {' '} <button onClick={this.increment}> + </button> {' '} <button onClick={this.decrement}> - </button> </p> ) } } Counter.propTypes = { value: PropTypes.number.isRequired, onIncrement: PropTypes.func.isRequired, onDecrement: PropTypes.func.isRequired } const render = () => ReactDOM.render( <Counter value={store.getState()} onIncrement={() => store.dispatch({ type: 'INCREMENT' })} onDecrement={() => store.dispatch({ type: 'DECREMENT' })} />, rootEl ) render() store.subscribe(render) ``` 运行效果如下: :-: ![](http://xiaoyulive.oss-cn-beijing.aliyuncs.com/imgs/react/009.png) 可以看到效果为点击 +/- 对应的 Count 数值也对应增加。 当然这只是一个很简单的例子,只是为了说明一些问题,实际应用中比这复杂得多。 ## 基本概念 一个 Redux 应用程序包括以下几个部分: ### Store Store 是一个数据存储池,用于保存View中的一些状态。 比如上述案例中的: ```js import { createStore } from 'redux' import reducers from './reducers' const store = createStore(reducers) ``` 创建了一个数据存储池 store,后面章节详细介绍。 ### State Store对象包含所有数据。如果想得到某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫做 State。 State 是view中的具体状态,使用 `store.getState()` 获取状态值,一个state只对应一个view。 比如上述案例中的: ```js <Counter value={store.getState()} /> ``` 将state传递给 Counter 组件,在组件中使用 `props.value` 接收。 ### Action Action 是把数据从应用传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说会通过 store.dispatch() 将 action 传到 store。 比如上述案例中的: ```js onIncrement={() => store.dispatch({ type: 'INCREMENT' })} onDecrement={() => store.dispatch({ type: 'DECREMENT' })} ``` 提交一个type为 `DECREMENT` 的Action以改变state 在上例中的 `reducers` 方法,接收两个参数,一个是 state 的状态,另一个参数叫 action,使用一个 type 属性区别 action 的具体行为。 ### Reducer Reducer 是具体指定 Action 将如何改变 State 状态的一个方法,接收上一个状态的状态值 previousState 和一个 action,返回新的状态值 newState。 比如上述案例中定义的的 `reducers` 函数,这个方法就是 reducer。 ```js const reducers = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } }; ```