尚硅谷-react教程-求和案例-异步action版-笔记

  • public/index.html
html 复制代码
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>redux</title>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
  • src/App.jsx
javascript 复制代码
import React, {Component} from 'react';
import Count from "./components/Count";

class App extends Component {
    render() {
        return (
            <div>
                <Count/>
            </div>
        );
    }
}

export default App;
  • src/index.js
javascript 复制代码
import React from "react";
import ReactDOM from 'react-dom'
import App from './App'

import store from './redux/store'

ReactDOM.render(<App/>,document.getElementById('root'))
// 检测redux中状态的变化,只要变化,就调用render
store.subscribe(()=>{
    ReactDOM.render(<App/>,document.getElementById('root'))
})
  • src/components/Count/index.jsx
javascript 复制代码
import React, {Component} from 'react';
// 引入store,用于获取redux中保存状态
import store from '../../redux/store'
// 引入actionCreator,专门用于创建action对象
import {createIncrementAction,createDecrementAction,createIncrementAsyncAction} from '../../redux/count_action'
class Count extends Component {
    // count已经交给了redux去管理了
    state = {carName:'奔驰c63'}

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

    // 加法
    increment=()=>{
        const {value} = this.selectNumber
        // 通知redux加value
        // store.dispatch({type:'increment',data:value*1})
        store.dispatch(createIncrementAction(value*1))
    }
    // 减法
    decrement=()=>{
        const {value} = this.selectNumber
        // store.dispatch({type:'decrement',data:value*1})
        store.dispatch(createDecrementAction(value*1))
    }
    // 奇数再加
    incrementIfOdd=()=>{
        const {value} = this.selectNumber
        const count = store.getState()
        if(count % 2 !== 0) {
            // store.dispatch({type:'increment',data:value*1})
            store.dispatch(createIncrementAction(value*1))
        }
    }
    // 异步加
    incrementAsync=()=>{
        const {value} = this.selectNumber
        // setTimeout(()=>{
            // store.dispatch(createIncrementAction(value*1))
        // },500)
        store.dispatch(createIncrementAsyncAction(value*1,500))
    }
    render() {
        return (
            <div>
                <h1>当前求和为:{store.getState()}</h1>
                <select ref={c => this.selectNumber = c}>
                    <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}>当前求和为奇数再加</button>&nbsp;
                <button onClick={this.incrementAsync}>异步加</button>&nbsp;
            </div>
        );
    }
}

export default Count;
  • src/components/redux/constant.js
javascript 复制代码
/**
 * 该模块是用于定义action对象中type类型的常量值,目的只有一个:
 *      便于管理的同时防止程序员单词写错
 */
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
  • src/components/redux/count_action.js
javascript 复制代码
/*
* 该文件专门为Count组件生成action对象
* */
import {INCREMENT,DECREMENT} from './constant'
/*
// 版本1
function createIncrementAction (data) {
    return {type:'increment',data}
}

function createDecrementAction (data) {
    return {type:'decrement',data}
}*/

// 版本2
// 同步action,就是指action的值为Object类型的一般对象
export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})

// 异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的
export const createIncrementAsyncAction = (data,time) => {
    return (dispatch)=>{
        setTimeout(()=>{
            dispatch(createIncrementAction(data))
        },time)
    }
}
  • src/components/redux/count_reducer.js
javascript 复制代码
/*
* 1.该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数
* 2.reducer函数会接到两个参数,分别为: 之前的状态(preState),动作对象(action)
* */
import {INCREMENT,DECREMENT} from './constant'
// 初始化版本1
/*
function countReducer(preState,action) {
    if(preState === undefined) preState = 0
    // 从action对象中获取:type,data
    const {type,data} = action
    // 根据type决定如何加工数据
    switch (type) {
        case 'increment': // 如果是加
            return preState + data
        case 'decrement': // 如果是减
            return preState - data
        default:
            return preState
    }
}*/

// 初始化版本2
const initState = 0
export default function countReducer(preState=initState,action) {
    // 从action对象中获取:type,data
    const {type,data} = action
    // 根据type决定如何加工数据
    switch (type) {
        case INCREMENT: // 如果是加
            return preState + data
        case DECREMENT: // 如果是减
            return preState - data
        default:
            return preState
    }
}
  • src/components/redux/store.js
javascript 复制代码
/*
*  该文件专门用于暴露一个store对象,整个应用只有一个store对象
* */

// store.js
//引入createStore,专门用于创建redux中最为核心的store对象
import {createStore,applyMiddleware} from 'redux'
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
//引入redux-thunk,用于支持异步action
import {thunk} from 'redux-thunk'
//导出store
export default createStore(countReducer,applyMiddleware(thunk))
复制代码
## 3.求和案例_redux异步action版
    (1).明确:延迟的动作不想交给组件自身,想交给actionA
    (2).何时需要异步action:想要对状态进行操作,但是具体A的数据靠异步任务返回
    (3).具体编码:
        1).yarn add redux-thunk,并配置在store中
        2).创建action的函数不再返回一般对象,而是一个函数,该函数中写异步任务
        3).异步任务有结果后,分发一个同步的action去真正操作数据
    (4).备注:异步action不是必须要写的,完全可以自己等待异步任务的结果了再去分发同步action
相关推荐
Source.Liu5 分钟前
【A11】服务器底层权限表笔记
运维·服务器·笔记
噜~噜~噜~39 分钟前
钢琴入门-基础乐理:第1讲到第3讲笔记
笔记·钢琴入门
坤坤子吖44 分钟前
Linux 线程概念与控制——线程创建、退出与等待
linux·开发语言·c++·笔记·学习
qq_284274051 小时前
间歇运动机构与机械设计概论:棘轮与槽轮机构运动系数、零件失效与强度刚度准则、结构工艺性清根及标准件(含考点)
笔记·学习·平面·自动化·制造
于眠牧北2 小时前
雷电模拟器9/14搭配charles抓取自带浏览器接口9/14
经验分享·笔记·git
Answer1st9 小时前
【嵌入式模块】UART通信模块
笔记
和侧10 小时前
离子注入后为什么必须配套退火工艺?
笔记·学习
TheBlackHoleLab14 小时前
【Vulnhub系列】DarkHole1: 渗透测试笔记,没有踩渗透的坑,却踩到了虚拟机平台的坑,人生处处是大坑
笔记·vulnhub·easy·darkhole1
ACP广源盛1392462567314 小时前
硬件选型笔记:GSV2231@ACP,DP1.4 MST 一进三出多屏扩展方案评估
笔记·硬件架构·视频·mst·国产芯片