react-redux从零手写求和案例

目前正在学习尚硅谷的react 觉得react-redux稍微有点绕,特此写文章捋清思路
1、安装和构建redux相关文件
安装:

npm i redux -S
npm i react-redux -S
npm i react-thunk -S

构建:
1、进入src文件夹 创建redux目录
2、redux中需要的东西有:
在这里插入图片描述

constant.js 用于定义常量
count_action.js 用于声明接下来要对redux执行的动作 比如+1操作,则为{type:‘increment’,data:1}
count_reducer.js 实际操作的函数 执行action告诉它的操作type,对redux的数据state进行真实的改动
store.js 该文件中通过createStore创建store
在这里插入图片描述
为了更好地了解store.js,首先要了解这个图,我们从store开始看
store相当于管理员(餐厅老板),reducer相当于仓库(后厨),而后厨中的厨子掌握了相应的做菜方法,餐厅老板说要后厨做什么菜,则只需要提供原材料(preState)和下达命令(action),后厨做好之后端出来(newState),最后老板给客人(components)上菜
作为老板,在store.js文件中,我们需要开店(createStore),同时店里需要引入后厨(假设waiter暂时不雇佣)
store.js:

import { applyMiddleware, createStore } from 'redux'

import countReducer from './count_reducer'
import thunk from 'redux-thunk'

export default createStore(countReducer,applyMiddleware(thunk))

其中thunk是异步时需要用到的 具体为什么要用 待会action的时候说
下一步是写reducer

count_reducer.js:

import { INCREMENT, DECREMENT } from './constant'

// reducer函数会接受两个参数,一个是之前的状态preState 一个是action动作对象
const initState = 0;
export default function countReducer(preState = initState, action) {
  // console.log('pre:', preState,'act:', action);
  const { type, data } = action;
  switch (type) {
    case INCREMENT:
      return preState + data;
    case DECREMENT:
      return preState - data;
    default:
      return preState;
  }
}

之后是action的内容

count_action.js:

import { INCREMENT, DECREMENT } from './constant'
export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})

export const createIncrementAsyncAction = (data,time) => {
    return (dispatch) => {
        setTimeout(() => {
            // console.log(dispatch)
            dispatch(createIncrementAction(data))
        },time)
    }
}

接着刚刚说一下为什么要用redux-thunk,因为redux规定,对于这些action,默认情况下只允许传入对象形式,而异步的需要返回一个函数(不写函数的话没办法让他等待,写await又不能接收promise)

之后是UI组件和container的合并文件

Count.jsx(containers/Count/index.jsx)

import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  createIncrementAction,
  createDecrementAction,
  createIncrementAsyncAction,
} from '../../redux/count_action';

class Count extends Component {
  //   state = { count: 0 };

  increment = () => {
    // console.log(this.selectNumberRef)
    const { value } = this.selectNumberRef;
    // store.dispatch(createIncrementAction(value * 1));
    this.props.increment(value * 1);
  };
  decrement = () => {
    const { value } = this.selectNumberRef;
    // store.dispatch(createDecrementAction(value * 1));
    this.props.decrement(value * 1);
  };
  incrementOfOdd = () => {
    const { value } = this.selectNumberRef;

    if (this.props.count % 2 !== 0) this.props.increment(value * 1);
  };
  incrementAsync = () => {
    const { value } = this.selectNumberRef;
    this.props.incrementAsync(value * 1, 500);
  };
  render() {
    // console.log('UI props:', this.props);
    return (
      <div>
        <h1>当前求和为:{this.props.count}</h1>
        <select
          ref={(c) => {
            this.selectNumberRef = c;
          }}
        >
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
        <button onClick={this.incrementOfOdd}>当前求和为奇数再加</button>
        <button onClick={this.incrementAsync}>异步加</button>
      </div>
    );
  }
}

export default connect((state) => ({ count: state }), {
  increment: createIncrementAction,
  decrement: createDecrementAction,
  incrementAsync: createIncrementAsyncAction,
})(Count);

有点忘记ref是干嘛的了 特意回顾了一下,ref可以是字符串形式(官方已经不推荐)或者回调函数的形式,渲染的时候他会自动调用该函数,并传入一个参数(c),该参数就是真实dom,通过{ value } 解构出其中的值,就是我们想要的数据

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值