美文网首页
React redux ( 状态管理器 )

React redux ( 状态管理器 )

作者: Poiey | 来源:发表于2019-12-24 09:39 被阅读0次

简介 : Redux 是 JavaScript 状态管理器。跟 Vuex 很相似,但又不同于 Vuex。

Redux 的三大原则

  1. 单一数据源- 整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store 中。

  2. state 是只读的- 唯一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象。

  3. 使用纯函数来执行修改- 为了描述 action 如何改变 state tree ,你需要编写 reducers。

安装 :yarn add redux | | npm install --save redux

创建一个简单的 redux 顺序
1.首先创建一个 store / index.js 文件 用来作为仓库。

import { createStore } from 'redux'

const reducer = (state,action)=>{
    if(action.type==="ADD_GOODS"){
        let newCards = JSON.parse(JSON.stringify(state))
       let index = state.cards.findIndex(item=>item.id === action.item.id)
       if(index>-1){
            newCards.cards[index].num++
        }else{
            newCards.cards.push(action.item)
        }
        return newCards
     }else if(action.type === 'ADD_CARDS'){
        let newCards = JSON.parse(JSON.stringify(state))
        let index = state.cards.findIndex(item=>item.id === action.item.id)
        if(index>-1){
            newCards.cards[index].num++
        }else{
            newCards.cards=[...newCards.cards,action.item]
            
        }
        return newCards
     }else if(action.type === 'DELETE_GOODS'){
        let newCards = JSON.parse(JSON.stringify(state))
        let index = state.cards.findIndex(item=>item.id === action.item.id)
        if(state.cards[index].num>1){
            newCards.cards[index].num--
        }else{
            newCards.cards.splice(index,1)
        }
        return newCards
     }
     else{
        return{
            cards:[]
        }
     }
}

const stort = createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())

export default stort

2.哪里需要用到仓库中数据的地方就引入 store

import store from './stort'

3.相关方法

 -维持应用的 state;

 -提供 getState()方法获取 state;

 -提供 dispatch(action)方法更新 state;

 -通过 subscribe(listener) 注册监听器;

 -通过 subscribe(listener) 返回的函数注销监听器。

通过 dispatch 派发一个 action --> 仓库中判断类型并且改变仓库中的数据 ( 深拷贝数据 ) --> 监听仓库中数据的变化,并且改变组件中的数据

相关文章

网友评论

      本文标题:React redux ( 状态管理器 )

      本文链接:https://www.haomeiwen.com/subject/cnsxoctx.html