Redux

Redux

Redux 是 JavaScript 状态容器,提供可预测化的状态管理。一般与React一同使用。

Redux使用普通对象存储 state,但是state不能随意被修改。

通过action(普通对象)传递数据变化的载荷,即发生变化的条件(type)和新数据:

{
  type: '', // 固定写法
  newState,
  ...
}

通过reducer具体描述数据如何变化。

三大原则

  • 单一数据源:整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store中。
  • State只读:唯一改变state的方法就是触发action。
  • 使用纯函数来执行修改:执行修改操作的reducer函数必须是纯函数,即不能改变入参(state),不能执行有副作用的操作。

基础

Action

action就是一个对象:

{
  type: '', // 固定写法,指定将要执行哪些操作
  newState,  // 即将参与state更新的数据
  ...
}

一般使用Action创建函数返回action对象:

function actionCreator(data) {
  return {
    type: 'someString',
    data
  }
}

发起action:

dispatch(actionCreator(data));
Reducer

reducer具体描述了如何根据action更新state,并返回更新后的state。

function someReducer(state = initialState, action) {
  switch(action.type) {
    case 'string':
      // 执行没有副作用的操作,这里不能直接更改原state,一般使用深复制生成新的state对象
      ...
      return newState;// 返回新的更新后的state
    default:
      return state;// 返回原state
  }
}

拆分reducer并将每个返回值合并为一个state

当reducer函数较复杂时可进行拆分,让每个子reducer分别处理部分state数据,并最终合并。

使用Redux提供的combineReducers()实现:

import { combineReducers } from 'redux'

function someReducer(state, action) {}

function otherReducer(state, action) {}

export default combineReducers({
  someReducer,
  otherReducer
})

或者:

import { combineReducers } from 'redux'
import * as reducers from './reducers' // 包含所有reducer的js文件

const todoApp = combineReducers(reducers)
Store

使用合并后的reducer创建一个store:

import { createStore } from 'redux'
let store = createStore(todoApp); // todoApp是合并后的reducer

createStore() 的第二个参数是可选的, 用于设置 state 的初始状态。

使用创建好的 store 发起 action 更新state:

import { someAction,otherAction } from './actions'

store.dispatch(someAction(param))
store.dispatch(otherAction(otherParam))

获取当前state值:

store.getState()

监听state的更新,每次更新时执行操作,它返回一个函数用来注销监听器:

const unsubscribe = store.subscribe(() =>
  console.log(store.getState())
)

// 停止监听 state 更新
unsubscribe();

高级

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@前端攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值