redux求和案例精简版

redux求和案例精简版_第1张图片
1.在src目录下创建redux文件夹

  • redux
    • store.js
    • count_reducers.js

安装 redux npm install redux

store.js
// 引入createStore,专门用于创建redux中最为核心的store对象
import  {createStore}  from 'redux'

// 引入为count组件服务的reducer
import countReducer from './count_reducers'

// 暴露出去 createStore调用时要创建一个为其服务的reducer
export default createStore(countReducer)
count_reducers.js
// 该文件用于创建一个count组件服务的reducer,reducer本质就是一个函数
// reducer会接收到两个参数,分别为之前的preState,动作对象action

let initState = 0

export default function countReducer (preState=initState,action){
    //从action中结构出type,data
    const {type,data} = action
    switch(type){
        case 'addcount':
            console.log(preState,data)
            return preState + data
        case 'redcount':
            return preState - data
        default:
            return preState
    }
}
count.jsx
import React, { Component } from 'react'
import store from '../../redux/store'
export default class count extends Component {
 
    //加
    addCount = ()=>{
        let {value} = this.selectInp
        store.dispatch({
            type:'addcount',
            data:value*1
        })
       
    }
    //减
    redCount = ()=>{
        let {value} = this.selectInp
        store.dispatch({
            type:'redcount',
            data:value*1
        })
    }
    //异步添加
    addAsyncCount = ()=>{
        let {value} = this.selectInp
        setTimeout(()=>{
            store.dispatch({
                type:'addcount',
                data:value*1
            })
        },1000)
    }
    //奇数相加
    addOddCount = ()=>{
        let {value} = this.selectInp
        let count = store.getState()
        if(count%2!==0){
            store.dispatch({
                type:'addcount',
                data:value*1
            })
        }
    }

    // componentDidCatch(){
    //     //检测redux中状态的变化,只要变化,就调用render
    //     store.subscribe(()=>{
    //         this.setState({})
    //     })
    // }

    handleChange = ()=>{
        console.log(this.selectInp.value)
    }
  render() {
    return (
      <div>
          <h3>计算结果{store.getState()}</h3>
          <select id="selector" ref={c=>this.selectInp=c} onChange={this.handleChange}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
        </select>
          <button onClick={this.addCount}></button>
          <button onClick={this.redCount}></button>
          <button onClick={this.addAsyncCount}>异步添加</button>
          <button onClick={this.addOddCount}>奇数添加</button>
      </div>
    )
  }
}

提供 getState() 方法获取 state;
提供 dispatch(action) 方法更新 state;
通过 subscribe(listener) 注册监听器;

index.js中检测store中状态的改变,一旦发生改变重新渲染

redux求和案例精简版_第2张图片

你可能感兴趣的:(react,react,前端)