美文网首页
Redux学习

Redux学习

作者: lmmy123 | 来源:发表于2018-10-26 22:08 被阅读2次
Redux是 状态管理器,由Flux演变而来

应用中所有的 state 都以一个对象树的形式储存在一个单一的 store 中。 惟一改变 state 的办法是触发 action,一个描述发生什么的对象。 为了描述 action 如何改变 state 树,你需要编写 reducers

import { createStore } from 'redux'
// 编写一个reducer
function counter(state=0,action) {
  switch(action.type){
   case 'INCREMENT':
     return state + 1;
   case 'DECREMENT':
     return state - 1;
    default: 
     return state;
  }
}

// 创建 Redux store 来存放应用的状态
// API 是  { subscribe,dispatch, getState }
let store = createStore(counter)
// 可以手动订阅更新,也可以事件绑定到视图层
store.subscribe( ()=>console.log(store.getState()) )

// 改变内部state唯一方法是 dispatch一个action
store.dispatch({type: 'INCREMENT'}) 
三大原则
  • 单一数据源
    唯一的store
  • state是只读的
    唯一改变state的方式是触发action, 不能只修修改state
  • 使用纯函数来执行修改
    Reducer是纯函数,接收先前的state和action,并返回一个新的state
基础
Action

定义用户交互的行为

const ADD_TODO = 'ADD_TODO'
const action = {
  type: ADD_TODO,
  text:'sdfjkwope'
}

Action 创建函数
Action 创建函数生成action的方法

function addTodo(text){
    return {
      type: ADD_TODO,
      text
  }
}
store.dispatch(action) // 触发action 
Reducer

纯函数,响应action,并更新state
不要做这些

  • 修改传入的参数,不能修改state
  • 执行有副作用的操作,如API请求和路由跳转
  • 调用非纯函数,如Data.now(),Math.random()
    拆分/组合Reducer
    combineReducers()
import { combineReducers } from 'redux'
// 合并 visibilityFilter,todos两个reducer
const todoApp = combineReducers({
  visibilityFilter,
  todos
})
Store

Store是单一的,职责:

  • 维持应用的state
  • 提供 getState() 方法获取state
  • 提供 dispatch(action)方法更新state
  • 通过 subscribe(listener)注册监听器
  • 通过 subscribe(listener)返回的函数注销监听器

创建store

import { createStore } from 'redux'
import todoApp from  './reducers'
let store = createStore(todoApp)

相关文章

网友评论

      本文标题:Redux学习

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