redux 和 react-redux 使用笔记

redux就是一个数据管理工具

  • action ---数据层,公共约定
  • reducer --根据dispatch发布更新处理action数据,建议返回新state。
  • store ---1 dispatch发布事件,2getState()获取stage,3subscribe监听触发 事件 参考例子 git>https://github.com/mazhenxiao/ProcessTimeLine.git

redux 简单实例

import { createStore } from 'redux';
//action 实例,就是一个数据结构约定,type为该数据识别码
let db = {
 "type":"storeIndex",
 "data":{
     "list":[],
     "show":true
 }
}
//reducer实例,处理触发器触发后如何返回数据。
 let reducer=(state=db,action)=>{
   let {data,type} = action;
    if(type=="storeIndex"){
        return Object.assign({},state,action) //建议返回新对象不直接改初始对象
    }
    return state;
}
//store实例,绑定reduce
let store = createStore(reducer);
//store监听实例,类似dom层addEventlistener
     store.subscribe(() => 
             //store.getState(),返回reducer处理过的数据
             console.log(store.getState()) 
      );
//store.dispatch 发布实例
      store.dispatch({
          "type":"storeIndex",
          "data":{
               "list":[1,2,3,4,5,6],
               "show":true
           }
      })

export default store
复制代码

react-redux,我不苟同但是开发只能随大溜,公共约定。

  • 组件
  • connect 绑定组件

react-redux 实例

1、Provider 组件绑定

import React,{Component} from "react";
import {Provider} from "react-redux";
import { BrowserRouter as Router,Route} from 'react-router-dom';
import store from "@js/redux";
import ViewIndex from "@view/index";

class Prouter extends Component{
    render(){
        return <Provider store={store}> //store 参照redux生成
                     <Router>
                         <Route exact path="/" component={ViewIndex} />
                    </Router> 
               </Provider>
    }
}
export default Prouter
复制代码

2、connect 绑定组件,注入redux的action到组件的props,也是关键步骤,并且蹩脚。

以高阶函数绑定当前组件

  • mapStateToProps: 相当于过滤filter,返回当前项目所需action
  • mapDispatchToProps: 在props里注入一个函数,并给函数注入参数dispatch,用来发布更新action,此处实例我自定义了个onLoad在componentDidMount中执行,并将dispatch 提取出来在当前类使用。
import React, { Component } from "react";
import controllerIndex from "./controller-index";
import actionIndex from "./action-index";
import {connect} from "react-redux";

class VIewIndex extends Component{
    constructor(props, context){
        super(props, context);
        this.dispatch=null;
    }
 componentDidMount(){
        this.props.onLoad(dispatch=>this.dispatch=dispatch);
    }
 Event_Click_Getstate(event){
         this.dispatch({
            type:"storeIndex",
            data:{
               list:[{
                   startTime:"1234123"
               }]
            }
         }) 
     }
    render(){
        let {storeIndex} = this.props
        return <article onClick={this.Event_Click_Getstate.bind(this)}>
              {
                   storeIndex.data.list.map((da,ind)=>{
                    return <p key={ind}>{da.startTime}</p>
                  })  
              }
        </article>
    }
}
//过滤当前所需action
const mapStateToProps=(state)=>{ 
    return {storeIndex:state.storeIndex}
}
// 在props里注入自定义函数,为了返回dispatch用来发布action
const mapDispatchToProps=(dispatch)=>{
   return {
        onLoad(callback){ callback(dispatch) }
   }
}

//此处为关键所在
export default connect(mapStateToProps,mapDispatchToProps)(VIewIndex);
复制代码

源码解析

一直吐槽为神马不直接注入到组件,还得去高阶嵌套,于是翻阅react-redux到Provider,发现他只是如实中转了store

 class Provider extends Component {
        getChildContext() {
          return { [storeKey]: this[storeKey], [subscriptionKey]: null }
        }

        constructor(props, context) {
          super(props, context)
          this[storeKey] = props.store;
        }

        render() {
          return Children.only(this.props.children)
        }
    }

复制代码

既然已经开始处理子元素了,为什么不直接向下逐层添加props,于是我就尝试去添加,发现报错,于是翻开react源码找原因,发现竟然冻结了子元素的props属性Object.freeze(childArray); 所以无法直接逐层注入,否则使用react.Children.map 方法可以逐一或递归注入到props里

 // Children can be more than one argument, and those are transferred onto
  // the newly allocated props object.
  var childrenLength = arguments.length - 2;
  if (childrenLength === 1) {
    props.children = children;
  } else if (childrenLength > 1) {
    var childArray = Array(childrenLength);
    for (var i = 0; i < childrenLength; i++) {
      childArray[i] = arguments[i + 2];
    }
    {
      if (Object.freeze) {
        Object.freeze(childArray);
      }
    }
    props.children = childArray;
  }
复制代码

connect 事件发布mapDispatchToProps,使用了recux的bindActionCreators 方法绑定函数并传入dispatch作为参数

export function whenMapDispatchToPropsIsObject(mapDispatchToProps) {
  return (mapDispatchToProps && typeof mapDispatchToProps === 'object')
    ? wrapMapToPropsConstant(dispatch => bindActionCreators(mapDispatchToProps, dispatch))
    : undefined
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Redux是一个独立的JavaScript库,用于管理应用程序的状态。它提供了一个可预测的状态容器,可以在整个应用程序中共享。Redux通过单向数据流来管理状态,使得状态的变化变得可控和可预测。 React-ReduxRedux的官方绑定库,它提供了一些与React集成的功能,使得在React应用中使用Redux更加方便。React-Redux提供了一个Provider组件,它可以将Redux store传递给整个应用程序。它还提供了一个connect函数,它可以将Redux store中的状态映射到React组件的props中,使得React组件可以轻松地访问Redux store中的状态。 ### 回答2: Redux是一个用于JavaScript应用程序的状态容器,它提供了一个可预测且可维护的方式来管理应用程序的状态。Redux的核心概念是“单一数据源”,即将整个应用程序的状态存储在单一对象树中,并且任何组件都可以访问和修改该状态树的任意部分。 react-redux是一个与React紧密集成的Redux绑定库。它提供了一组React组件和API,使得使用Redux在React应用程序中更加容易。 reduxreact-redux之间的关系可以理解为Redux是一种状态管理库,而react-reduxRedux与React之间的纽带。 具体来说,react-redux提供了两种主要的API:Provider和connect。 Provider是一个React组件,允许我们将应用程序的Redux存储连接到React组件树中的所有组件。在Provider组件内部,可以通过store属性传递Redux存储对象,使得所有组件都可以访问该存储。 connect是一个高阶组件,用于将React组件连接到Redux存储中的状态和操作。通过connect,我们可以在React组件中访问Redux状态,以及派发Redux操作。connect本质上是一个函数,它接收一个组件作为参数并返回一个新的连接了Redux存储的组件。 总之,reduxreact-redux之间的区别在于,redux是一个独立的状态管理库,而react-reduxRedux和React之间的桥梁,帮助React应用程序连接到Redux存储,并访问存储中的状态和操作。 ### 回答3: ReduxReact-Redux都是在React项目中使用JavaScript库。Redux是一个JavaScript状态容器,用于管理应用程序中的所有状态。Redux允许将状态存储在一个单一的地方,以便在整个应用程序中共享该状态。React-Redux是React的一个库,用于与Redux一起使用,以便在React组件中访问和更新Redux状态。 Redux通过store提供一个单一的状态树,包含了整个应用程序的状态。通过使用store中的action和reducer,Redux可以跟踪状态的所有更改。这可以帮助开发人员更容易地调试和管理代码。但是,使用Redux需要一定的时间和精力来管理各个状态,尤其在较大的代码库中尤其如此。 React-Redux库是Redux的一个扩展,它提供了一组工具来帮助React组件访问和更新Redux状态。通过提供Provider组件,React-Redux使得Redux存储的状态可以传递到整个应用程序中的所有组件。通过使用connect函数和mapStateToProps和mapDispatchToProps参数,React-Redux允许开发人员将Redux状态映射到React组件中。这样,开发人员就可以根据需要将Redux状态作为props传递给组件,并且可以更方便地将状态更改传递回Redux store。 总之,Redux为React提供了一个易于管理的状态储存架构,以帮助应用程序开发人员管理和跟踪应用程序状态。React-Redux是一组工具,它使开发人员可以更方便地在React组件中使用Redux,从而帮助开发人员更快地开发应用程序。两者的区别在于Redux是包含整个应用程序状态的状态容器,而React-Redux则是提供了一组工具,以帮助开发人员更方便地在React组件中使用Redux状态。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值