React-redux的原理解析及基本使用

当一个React项目组件层级越来越深,页面越来越多的时候,数据在各个组件层级和页面之间传递的需求就会比较多。这时候就需要了React-redux
ReduxReact的一个状态管理库Redux简化了React中的单向数据流。 Redux将状态管理完全从React中抽象出来。

一、 Redux的工作流程图

在这里插入图片描述

React Component —— 页面上的组件 (借书的用户)
Store —— 存储数据的公共区域(相当于图书馆的管理员)
Action Creators —— 数据传递的过程(借书的时候说的话做的事)
Reducers —— 记录本 (还书和借书的地方)

React中,组件连接到 Redux ,如果要访问 Redux,需要派出一个包含 id和负载(payload) 的 ActionAction 中的 payload 是可选的,Action 将其转发给 Reducer

Reducer收到Action时,通过 switch…case 语法比较 Actiontype。 匹配时,更新对应的内容返回新的 state

Redux状态更改时,连接到Redux的组件将接收新的状态作为props。当组件接收到这些props时,它将进入更新阶段并重新渲染 UI

二、Redux和React-redux的使用

1、redux安装
npm i redux

使用Redux, 所有的数据都存在store之中,在src的目录下创建一个名为store的文件夹 在创建一个index.js

在index.js 文件当中

import { createStore } from 'redux'; // 引入创建store的方法
import reducer from './reducer';    

const store = createStore(reducer);

export default store;

store是一个图书的管理员 它需要一个笔记本去帮忙管理这些图书 所以在store文件夹目录下面创建 reducer.js (reducer是一个纯函数)

//这个数据的初始值
import { CHANGE_VALUE, SUBMIT_TYPE, SPLICE_TYPE, INIT_LIST_ACTION} from '../ActionTypes';

const defaultState = {
    values: '',
    list: []
};
export default (state = defaultState , action) =>{
    if(action.type === CHANGE_VALUE){
        const newState = JSON.parse(JSON.stringify(state));
        newState.values = action.values;
        return newState;
    }

    if(action.type === SUBMIT_TYPE){
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.push(newState.values);
        newState.values = '';
        return newState;
    }
    if(action.type === SPLICE_TYPE){
        const newState = JSON.parse(JSON.stringify(state));
        newState.list.splice(action.index, 1);
        return newState;
    }

    if(action.type === INIT_LIST_ACTION){
        const newState = JSON.parse(JSON.stringify(state));
        newState.list = action.data;
        return newState;
    }
    return state;
}

创建一个组件 test.js和store同级

import React, { Component } from 'react';
import {  Button, Input, List} from 'antd';
import store from './store';
import { getInputChangeAction, getInputSubmitAction, getInputListAction, getInitList} from './actionCreators';
import { CHANGE_VALUE, SUBMIT_TYPE, SPLICE_TYPE, GET_INIT_LIST} from './ActionTypes';

   class test extends Component{

      constructor(props){
        super(props);
        this.state= store.getState();
        this.submit = this.submit.bind(this);
        this.changes = this.changes.bind(this);
        this.handChange =this.handChange.bind(this);
        this.listClick =this.listClick.bind(this);
        store.subscribe(this.handChange);
      }

    componentDidMount(){
    }

    changes(e){
        
        let type = CHANGE_VALUE;
        let values = e.target.value;
        const action = getInputChangeAction(type, values);
        store.dispatch(action);
    }

    handChange(){
        this.setState(store.getState());
    }

    submit(){
        let type = SUBMIT_TYPE;
        const action = getInputSubmitAction(type);
        store.dispatch(action);
    }

    listClick(index){
        let type = SPLICE_TYPE;
        const action = getInputListAction(type, index);
        store.dispatch(action);
    // 父 -> 子  属性传值 this.props去接收  
    // 子 -> 父  属性传函数名并且改变this的指向 this.props去调用父组件的方法 this.props.zzz(this.props.dddd)  
    }

    render(){
        return (
            <div>
                <div>
                    <Input 
                    value={this.state.values}
                    placeholder= 'todo list' 
                    onChange ={this.changes}
                    style={{ width: '200px', height: '30px'}} />
                    <Button 
                    onClick ={this.submit}
                    type="primary"
                    >提交
                  </Button>
                </div>
                <List 
                    style={{ width: '200px'}}
                    bordered
                    dataSource={this.state.list}
                    renderItem={item => (<List.Item onClick={this.listClick}>{item}</List.Item>)}
                />
            </div>
        )
    }
}

    export default test;

和test.js同级创建actionCreators.js和ActionTypes.js ,ActionTypes.js是为了写一个声明变量的地方,方便代码管理和优化,写一个共同区域 调用时导入即可

actionCreators.js

export const getInputChangeAction = (type, values) => ({
    type, 
    values
})
export const getInputSubmitAction = (type) =>({
    type
})
export const getInputListAction = (type, index) =>({
    type, 
    index
})
export const initListAction = (type , data) =>({
    type,
    data
})
export const getInitList = (type) =>({
    type,
})

ActionTypes.js
export const CHANGE_VALUE = 'change_value';
export const SUBMIT_TYPE = 'submit_type';
export const SPLICE_TYPE = 'splice_type';
export const INIT_LIST_ACTION = 'init_list_action';
export const GET_INIT_LIST = 'get_init_lst';

Redux 中间件

在这里插入图片描述
中间件表示谁和谁的中间, 在图中 View在 Redux会派发一个ActionAction通过StoreDispatch方法派发给Store, Store接收到Action 连同之前State 一同传给ReducerReducer会返回一个新的数据给StoreStore然后去改变自己的State,这就是Redux的标准流程

Redux的中间件的中间是指 Action 和 Store 之间的关系

Action 只能是一个对象派发Store ,这个是在没有使用redux-thunk情况下;使用了redux-thunkAction 可以为一个函数 所以Dispatch方法就是ActionStore的中间件,就是对Dispatch方法的封装。

利用react-thunkDispatch方法进行封装,这时给Dispatch传入是一个对象,它会直接把这个对象传给Store ,如果Dispatch传入是一个函数的话,先执行 ,然后会根据传入的参数不同进行不同的事情。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值