(父界面)javascript
1.State
Store
对象包含全部数据。若是想获得某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫作 State。java当前时刻的 State,能够经过
store.getState()
拿到。reactimport { createStore } from 'redux'; const store = createStore(fn); const state = store.getState();
2. store.subscribe()
Store 容许使用
store.subscribe
方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。reduximport { createStore } from 'redux'; const store = createStore(reducer); store.subscribe(listener);
1. 值 :valuedom
value={store.getState()}
2.加函数 : async
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
3.减函数 :函数
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
import React from 'react' import ReactDOM from 'react-dom' import { createStore } from 'redux' import Counter from './components/Counter.js' import counter from './reducers/index.js' const store = createStore(counter) const rootEl = document.getElementById('root') const render = () => ReactDOM.render( <Counter value={store.getState()} onIncrement={() => store.dispatch({ type: 'INCREMENT' })} onDecrement={() => store.dispatch({ type: 'DECREMENT' })} />, rootEl ) render() store.subscribe(render)
Reducer 方法ui
判断action 的type值: 分别加1,减1.this
1. Reducer
Store 收到 Action 之后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫作 Reducer。spa
Reducer 是一个函数,它接受 Action 和当前 State 做为参数,返回一个新的 State。
const reducer = function (state, action) { // ... return new_state; };
export default (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: return state } }
import React, { Component } from 'react' import PropTypes from 'prop-types' class Counter extends Component { constructor(props) { super(props); this.incrementAsync = this.incrementAsync.bind(this); this.incrementIfOdd = this.incrementIfOdd.bind(this); } incrementIfOdd() { if (this.props.value % 2 !== 0) { //获取从父界面传入的value this.props.onIncrement() //获取从父界面传入的函数 } } incrementAsync() { setTimeout(this.props.onIncrement, 1000) //点击后延迟调用。 } render() { 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