redux的基本使用讲解,不会的还不进来看

140 阅读3分钟

本篇文章主要介绍Redux以及React-Redux的用法,我自己是用Vue开发的,所以对Vuex比较熟悉,Vue和React这两个框架,在我认为,Vue非常适合初学者上手,里面配置比较全面,而React比较适合有一定基础的人,React更让我们自由发挥,但是Vue3已经和React很像了,除了组合式API以及Hooks,Vue的状态管理使用的是Vuex,而React更偏向使用Redux,注意react-redux和redux是两个东西。

redux:

ok,一步步来,先看最简单的redux:

简单的redux

先安装  npm install redux

首先,了解仓库的概念,一般我们都用store.js来命名,注意:一个项目只有一个store.js。第二个概念reducer,reducer本质为一个函数,会接收两个参数,preState(之前的状态),action(动作对象)。而action是第三个概念,要执行的动作。好了,了解了这3个概念,下面我们来写一个的redux来管理数据。先看下我的目录结构:

image.png

先定义几个常量便于引用,没什么好说的!


/**
 * constant.js
 * 定义常量,便于引用  
 */

export  const INCREMENT = 'increment';
export  const DECREMENT = 'decrement';

/**
   count_action.js
 * 单独生成action对象
 * action就是你要执行的操作类型,这里定义两个操作 加与减
 */
//引入常量或者也可以自己随便定义
import { INCREMENT, DECREMENT } from './constant'
export const INCREMENTACTION = data => ({ type: INCREMENT, data });  //返回对象 type:操作类型,data:传入要操作的数据
export const DECREMENTACTION = data => ({ type: DECREMENT, data });

//count_reducer.js
//引入action
import { INCREMENT, DECREMENT } from './constant'
//状态默认值
const initState = 0;
export default function countRuducer(preState=initState, action) {
    const { type, data } = action;
    switch (type) {
        case INCREMENT:
            return preState + data;
        case DECREMENT:
            return preState - data;
        default:
            return preState;
    }
}

//store.js
import { createStore }  from 'redux';
import countReducer from './count_reducer';
export default createStore(countReducer);

image.png

这个地方需要注意哦,store.subscribe 当仓库数据变了,就会触发这个方法,不加这个,改变状态是刷新不了视图的,后面react-redux会对这个优化的。

这个redux已经完成了,下面我们来使用一下

//Home.jsx
import React, { Component } from 'react'
import store from '../redux/store'
import { INCREMENTACTION,DECREMENTACTION  } from '../redux/count_action'

export default class home extends Component {
    addCount = () => {
        const { selectVal } = this;
        store.dispatch(INCREMENTACTION(selectVal.value*1))
    }
    delCount = () => {
        const { selectVal } = this;
        store.dispatch(DECREMENTACTION(selectVal.value*1))
    }
    render() {
        return (
            <div>
                <div>
                    <h1>当前count:{store.getState()}</h1>
                </div>
                <select name="conunt" ref={c => { this.selectVal = c }} style={{ width: '100px' }}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                </select> &nbsp;
                <button onClick={this.addCount}>添加</button> &nbsp;
                <button onClick={this.delCount}>减少</button> 
            </div>
        )
    }
  
}

异步action

也很简单,同步action,就是指action的值为Object类型的一般对象。异步action,就是action值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。(Vuex中,mutations同步,actions异步,不一样)

//action.js
import { INCREMENT, DECREMENT } from './constant'
//同步action,就是指action的值为Object类型的一般对象
export const INCREMENTACTION = (data) => { return { type: INCREMENT, data } };
export const DECREMENTACTION = (data) => { return { type: DECREMENT, data } };


//异步action,就是action值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
export const ASYNCACTION = (data,time) =>{
  return (dispatch)=>{
    setTimeout(()=>{
        dispatch(INCREMENTACTION(data))
    },time)
  }
}
store.js
import { createStore,applyMiddleware  } from 'redux';
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
import countReducer from './count_reducer';
export default createStore(countReducer,applyMiddleware(thunk));

使用异步action跟同步的一样,直接dispatch:

store.dispatch(ASYNCACTION(818,2000))

贪多嚼不烂,先把redux弄懂。下篇文章讲react-redux!

image.png