Redux實例--1 Counter

一. index.js

(父界面)javascript

1. 知識點

1.State

Store 對象包含全部數據。若是想獲得某個時點的數據,就要對 Store 生成快照。這種時點的數據集合,就叫作 State。java

當前時刻的 State,能夠經過store.getState()拿到。react

import { createStore } from 'redux';
const store = createStore(fn);

const state = store.getState();

 

2. store.subscribe()

Store 容許使用store.subscribe方法設置監聽函數,一旦 State 發生變化,就自動執行這個函數。redux

import { createStore } from 'redux';
const store = createStore(reducer);

store.subscribe(listener);

2.父界面向Counter組件傳入三個值

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/index.js

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
  }
}

 

三. Counter.js

 

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
相關文章
相關標籤/搜索