Redux详解

rudux有三个核心理念,只有理解了它们才会理解的reudx

一、store 

         1.它是仓库对象,通过 createStore()创建;如:const store = createStore(reducer)             注意:createStore()接受的参数是reducer而不是 state数据

          2.三个函数

                  a.store.getState()  获取store中的state数据。

                   b.store.dispath()  修改store中的数据,store.dispath(action)传入一个新的action,重新触发reducer函数执行,并把新的action传到reducer的参数之中。

                   c.store.subscribe(()=>{})  订阅store,当store中的数据发生了变化,会自动执行回调函数。

二、action 

        1.它是一个普通的js对象 {type:"xxx",conten:xxxx}

        2.rudux中所有的数据变化必须通过派发action来更新

三、reducer

      1.它必须是一个纯函数

       2.它接受两个参数 

               a.store中当前保存的state

               b.本次更新的action

        3.返回值:作为state之后存储的state

        4.需要再reducer中编写修改state的逻辑代码

四、代码实践:

const initDate = {name:'zs',age:18}
const store = createStore( (state=initDate,action)=>{
  switch (action.type) {
    case "change_name":
      return { ...state, name: action.name };
    case "add_number":
      return { ...satisfies, counter: state.counter + action.num };
    default:
      return state;
  }
}} )


//组件开发中可以将store导出,组件中引入

//获取store中的数据
store.getState()
//修改store中的数据 dispath中传入的就是 action对象,它会重新触发reducer()执行,并把新的action传入
store.dispath({type:"change_name",name:'lisi'})
//订阅store中的数据,当store中的数据发生改变的时候会自动触发store.subscribe(()=>{})函数
store.subscribe(() => {
  console.log("数据变化:", store.getState());
});

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值