39_redux_counter应用_redux版本

时间:2024-06-09 20:07:50

一、下载

  要想使用redux,首先要下载它

  npm install --save redux

二、核心API

  1.createStore()

    作用:创建包含指定reducer的store对象

    编码:import {createStore} from 'redux'

       import counter from './reducers/counter'

       const store = createStore(counter)

  2.store对象

    作用:

      redux库最核心的管理对象

    它内部维护着:

      state

      reducer

    核心方法:

      getState()

      dispatch(action)

      subscribe(listener)

    编码:

      store.getState()

      store.dispatch({type:'INCREMENT',number})

      store.subscribe(render)

三、redux的三个核心概念

  1.action

    标识要执行行为的对象

    包含两个属性:

      type:标识属性,值为字符串,唯一,必要属性

      xxx:数据属性,值类型任意,可选属性

    例子:

      const action = {

        type:'INCREMENT',

        data:2

     }

    Action Creator(创建Action的工厂函数)

      const increment = (number) => ({type:'INCREMENT',number})

  2.reducer

    根据老的state和action,产生新的state的纯函数

    样例:

      export default function counter(state = 0, action){

        switch(action.type){

          case 'INCREMENT':

            return state + action.data

          case 'DECREMENT':

            return state - action.data

          default:

            return state

        }

      }

    注意:

      返回一个新的状态

      不要修改原来的状态

  3.store

    将state、action与reducer联系在一起发的对象

    如何得到这个对象?

      import {createStore} from 'redux'

      import reducer from './reducers'

      const store = createStore(reducer)

    此对象的功能?

      getState():得到state

      dispatch(action):分发action,出发reducer调用,产生新的state

      subscribe(listener):注册监听,当产生了新的state时,自动调用

四、代码:

项目结构:

  39_redux_counter应用_redux版本

  

import React from 'react';
import ReactDOM from 'react-dom';
import {createStore} from 'redux';

import App from './components/app';
import {counter} from './redux/reducers';

//生成store对象
const store = createStore(counter);//内部会第一次调用reduer函数得到初始state
console.log(store, store.getState());

function render() {
    ReactDOM.render(<App store={store}/>, document.getElementById('root'));
}

//初始化渲染
render()

//订阅监听(store中的状态变化了,就会自动调用重绘)
store.subscribe(render)

index.js

import React, {Component} from 'react'
import {INCREMENT, DECREMENT} from '../redux/action-types'

export default class App extends Component {

    increment = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1
        //2.调用store的方法更新状态
        this.props.store.dispatch({type: INCREMENT, data: number})

    };

    decrement = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1
        //2.调用store的方法更新状态
        this.props.store.dispatch({type: DECREMENT, data: number})
    };

    incrementIfOdd = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1
        //2.得到原本的count状态
        const count = this.props.store.getState()
        //3.判断,满足条件再更新状态
        if (count % 2 === 1) {
            //调用store方法更新状态
            this.props.store.dispatch({type: INCREMENT, data: number})

        }
    }

    incrementAsync = () => {
        //1.得到选择的增加数量
        const number = this.select.value * 1
        //启动延时定时器
        setTimeout(() => {
            this.props.store.dispatch({type: INCREMENT, data: number})
        }, 1000)
    };

    render() {
        const count = this.props.store.getState()
        // debugger
        return (
            <div>
                <p>click {count} times</p>
                <div>
                    <select ref={select => this.select = select}>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>&nbsp;
                    <button onClick={this.increment}>+</button>
                    &nbsp;
                    <button onClick={this.decrement}>-</button>
                    &nbsp;
                    <button onClick={this.incrementIfOdd}>increment odd</button>
                    &nbsp;
                    <button onClick={this.incrementAsync}>increment async</button>
                    &nbsp;
                </div>
            </div>
        )
    }
}

app.jsx

/*
* 包含所有action type的常量字符串
* */

export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

action-tupes.js

/*
* 包含n个reducer函数的模块
* */
export function counter(state = 0, action) {

    console.log('counter()', state, action)

    switch (action.type) {
        case 'INCREMENT':
            return state + action.data
        case 'DECREMENT':
            return state - action.data
        default:
            return state
    }

}

reducers.jsx