react的redux学习记录

本文详细介绍了如何在React中使用Redux进行状态管理,从创建简易的store和reducer,到添加常量文件优化,再到实现异步Action,逐步深入理解Redux的工作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.原理图

在这里插入图片描述

2.步骤

2.1 简易版

自己写action,其实就是返回一个对象(不包括异步action),src文件夹下创建redux文件夹,文件夹下有count_reducer.js和store.js文件

2.1.1 store.js

store.js,主要是创建store,并和renducers联系起来

import { createStore } from "redux";
import countRenducer from './count_reducer'
export default createStore(countRenducer)

2.1.2 count_reducer.js

count_reducer.js的作用主要是接收:preState,action,返回加工后的状态


const initState = 0 //初始化状态

export default function countReducer(preState = initState, action) {
   let { type, data } = action;
   switch (type) {
      case 'increment':
         return preState + data;
      case 'subtraction':
         return preState - data;
      default:
         return preState
   }
}

2.1.3 组件Count

import React, { Component } from "react";
import store from "../..//redux/store";

export default class Count extends Component {
  state = { carName: "奔驰c63" };
  componentDidMount() {
    store.subscribe(() => {
      this.setState({});
    });
  }
  //加法
  increment = () => {
    const { value } = this.selectNumber;
    store.dispatch({ type: "increment", data: value * 1 });
  };
  //减法
  decrement = () => {
    const { value } = this.selectNumber;
    store.dispatch({ type: "subtraction", data: value * 1 });
  };
  //奇数再加
  incrementIfOdd = () => {
    const { value } = this.selectNumber;
    if (store.getState() % 2 !== 0) {
      store.dispatch({ type: "increment", data: value * 1 });
    }
  };
  //异步加
  incrementAsync = () => {
    const { value } = this.selectNumber;
    setTimeout(() => {
      store.dispatch({ type: "increment", data: value * 1 });
    }, 500);
  };

  render() {
    //console.log('UI组件接收到的props是',this.props);
    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>
    );
  }
}


2.2 完整版

完整版比较简洁版在store.js同级目录下多了一个constant.js文件,主要是用于定义action对象中type类型的常量值,目的只有一个:便于管理的同时防止程序员单词写错

2.2.1 constant.js

export const INCREMENT ='increment';
export const SUBTRACTION = 'subtraction';

2.2.2 count_reducer.js

所以count_reducer.js也需要改变

import {INCREMENT,SUBTRACTION} from './constant'
const initState = 0 //初始化状态

export default function countReducer(preState = initState, action) {
   let { type, data } = action;
   switch (type) {
      case INCREMENT:
         return preState + data;
      case SUBTRACTION:
         return preState - data;
      default:
         return preState
   }
}

2.3 异步action版

如果我们延迟的动作不想交给组件自身,想交给action的话,那写法应该怎么做呢;这个版本跨度有点大,action Creators不是再由自己建立的了,所以也要在store.js同级目录创建一个count_action.js文件

2.3.1 store.js


//引入createStore,专门用于创建redux中最为核心的store对象
import { createStore,applyMiddleware } from "redux";
import countRenducer from './count_reducer'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
export default createStore(countRenducer,applyMiddleware(thunk))

2.3.2 count_action.js

/* 
	该文件专门为Count组件生成action对象
*/
import {INCREMENT,DECREMENT} from './constant'

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

//异步action,就是指返回的action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
//store的dispatch方法会判读传入值是函数还是对象,如果是函数,就给这个函数传参,参数值store的dispatch并且执行这个函数
export const createIncrementAsyncAction = (data,time) => {
	return (dispatch)=>{
		setTimeout(()=>{
			// store.dispatch({type:INCREMENT,data})
			// store.dispatch(createIncrementAction(data))
			dispatch(createIncrementAction(data))
		},time)
	}
}

2.3.3 Count组件

Count组件的dispatch调用就要重写了

import React, { Component } from "react";
import store from "../..//redux/store";
import {
  createIncrementAction,
  createSubtractionAction,
  createIncrementAsyncAction,
} from "../../redux/count_action";

export default class Count extends Component {
  state = { carName: "奔驰c63" };
  componentDidMount() {
    store.subscribe(() => {
      this.setState({});
    });
  }
  //加法
  increment = () => {
    const { value } = this.selectNumber;
    store.dispatch(createIncrementAction(value * 1));
  };
  //减法
  decrement = () => {
    const { value } = this.selectNumber;
    store.dispatch(createSubtractionAction(value * 1));
  };
  //奇数再加
  incrementIfOdd = () => {
    const { value } = this.selectNumber;
    if (store.getState() % 2 !== 0) {
      store.dispatch(createIncrementAction(value * 1));
    }
  };
  //异步加
  incrementAsync = () => {
    const { value } = this.selectNumber;
    store.dispatch(createIncrementAsyncAction(value * 1, 500));
  };

  render() {
    //console.log('UI组件接收到的props是',this.props);
    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>
    );
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值