react学习之redux基本使用(计算器为例)

1.redux设计思想

(1)Web 应用是一个状态机,视图与状态是一一对应的。
(2)所有的状态,保存在一个对象里面。

2.redux基本使用

(1)create-react-app myapp 创建一个raect项目
(2)yarn add redux 安装redux
(3)在src目录下建立一个store文件夹
(4)store下建立文件reducer.js和index.js
在这里插入图片描述

reducer.js

import {INCREMENT,DECREMENT} from "./actionType"
let initState={
    // 存3个初始值
    a:9,
    b:19,
    c:99
}
var reducer = (state=initState,{type,p=""})=>{
    var newState = {...state}
    // console.log(newState,p)
    switch(type) {
        case INCREMENT: 
            newState[p]++;
            return newState;
        case DECREMENT:
            newState[p]--
            return newState
        default:
            return state
    }
    
}
export default reducer

index.js

// 第一步:从redux包中引入createStore函数
// 第二步:引入reducer函数所在的文件
// 第三步:creaateStore函数里调用reducer
// 第四步:返回的对象赋值给store  store有三个常用对象 getState()负责取值
// ,dispatch负责修改值,subscribe负责订阅值的变化
import {createStore} from "redux"
import reducer from "./reducer"
var store = createStore(reducer)
export default store

应用中所有的 state 都以一个对象树的形式储存在一个单一的 store 中。 惟一改变 state 的办法是触发 action,一个描述发生什么的对象。 为了描述 action 如何改变 state 树,你需要编写 reducers。

3.redux核心概念和API

在这里插入图片描述
Store: Store 就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。Redux 提供createStore这个函数,用来生成 Store。如上图index.js。s

reducer是一个纯函数 Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。如上图reducer.js.

State: Store对象包含所有数据。如果想得到某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫做 State。使用store.getState()就能得到state对象。

action State 的变化,会导致 View 的变化。但是,用户接触不到 State,只能接触到 View。所以,State 的变化必须是 View 导致的。Action 就是 View 发出的通知,表示 State 应该要发生变化了。Action 是一个对象。其中的type属性是必须的,表示 Action 的名称。其他属性可以自由设置。例如:

const action = {
  type: 'ADD_TODO',
  payload: 'Learn Redux'
};

actionCreator View 要发送多少种消息,就会有多少种 Action。如果都手写,会很麻烦。可以定义一个函数来生成 Action,这个函数就叫 ActionCreator。下面是计算器组件中actionCreator文件

import {INCREMENT,DECREMENT} from "../../store/actionType"
export default{
    incAction(p){
        return {
            type: INCREMENT,
            p
        }
    },
    decAction(p){
        return{
            type: DECREMENT,
            p
        }
    }
}

store.dispatch(): store.dispatch()是 View 发出 Action 的唯一方法。它接受一个 Action 对象作为参数,将它发送出去。
store.subscribe(): Store 允许使用store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。store.subscribe方法返回一个函数,调用这个函数就可以解除监听。

let unsubscribe = store.subscribe(() =>
  console.log(store.getState())
);
unsubscribe();

下面是计算器组件的index.js文件

import React, { Component } from 'react'
import store from "../../store/index"
import actionCreator from "./actionCreator"
export default class Count extends Component {
    constructor(props){
        super(props)
        // 将初始值求和
        let sum = Object.values(store.getState()).reduce((a,b)=>a+b)
        this.state={
            // a: store.getState().a,   //将仓库里的值赋值给state
            sum
        }
        // 监听仓库里的值变化
        store.subscribe(this.change)
    }
    change=()=>{
        // let {a,b,c,sum }=this.state
        // 当store里数据修改的时候会执行这个回调函数
        this.setState({
            // num: store.getState().p
            // sum: store.getState().a+store.getState().b+store.getState().c
            sum:  Object.values(store.getState()).reduce((a,b)=>a+b)
        })
    }
    // 加
    inc(p){
        store.dispatch(actionCreator.incAction(p))   //修改仓库里的值,调用reducer函数
    }
    // 减
    dec(p){
        store.dispatch(actionCreator.decAction(p))
    }
    render() {
        // console.log(Object.entries(store.getState()))
        return (
            <div>
                {   
                // 将仓库里的数据转化为数组进行操作
                    Object.entries(store.getState()).map((item,index)=>{
                        // console.log(item[0])
                        return <div key={index}>
                                    <button onClick={this.dec.bind(this,item[0])}>-</button>
                                    {item[1]}
                                    <button onClick={this.inc.bind(this,item[0])}>+</button>
                        </div>
                    })
                }
                {this.state.sum}
            </div>
        )
    }
}

效果如图(样式自行添加)(逆战班冲冲冲)
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值