前言
本文介绍了一下React中的如何使用状态管理库
一、Redux是什么?
Redux 是一个独立的JavaScript 状态管理库, 非React内容之一 。 Redux 除了和 React 一起用外,还支持其它界面库。 它体小精悍(只有2kB,包括依赖)。
二、安装
npm install --save redux
三、核心概念
1.state 对象
通常我们会把应用中的数据存储到一个对象树中进行统一管理,我们把这个位置称为: state
2.state 是只读的
这里需要注意的是,为了保证数据状态的可维护性和测试,不推荐直接修改state中的原数据
3.通过纯函数修改 state
4.纯函数 – 函数式编程的一种概念
5.action 对象
-
我们对state 的修改是通过reducer 纯函数来进行的,同时通过传入的 action 来执行具体的操作 -
action 是一个对象 -
type 属性: 表示要进行操作的动作类型, 增删改查 -
payload属性: 操作 state 的同时传入的数据 -
但是这里需要注意的是,我们不直接去调用Reducer函数,而是通过Store对象提供的dispatch方法来调用
6.Store 对象 (负责存储的仓库)
- 为了对 steta, reducer, action,进行统一的管理和维护,我们需要创建一个Store对象(仓库)
四、redus 三大原则
五、基本使用
代码如下(示例):
import React from 'react'
import { createStore } from 'redux'
function reducer(state = {
name: '萝莉',
age: 20
}, action) {
switch (action.type) {
case 'edit_name':
return {
...state,
name: action.name
}
case 'edit_age':
return {
...state,
age: action.age
}
}
return state
}
let store = createStore(reducer)
console.log(store);
store.subscribe(() => {
console.log(store.getState());
})
store.dispatch({
type: 'edit_name',
name: '富婆'
})
store.dispatch({
type: 'edit_age',
age: 18
})
function App() {
return (
<div>
</div>
);
}
export default App;
六、combineReducers
核心概念
基于 Redux 的应用程序中最常见的 state 结构是一个简单的 JavaScript 对象,它最外层的每个 key 中拥有特定域的数据。类似地,给这种 state 结构写 reducer 的方式是分拆成多个 reducer,拆分之后的 reducer 都是相同的结构(state, action),并且每个函数独立负责管理该特定切片 state 的更新。多个拆分之后的 reducer 可以响应一个 action,在需要的情况下独立的更新他们自己的切片 state,最后组合成新的 state。
Redux 提供了 combineReducers 去实现这个模式。这是一个高阶 Reducer ,他接收一个拆分后 reducer 函数组成的对象,返回一个新的 Reducer 函数。
作用
combineReducers 辅助函数的作用是,把一个由多个不同reducer函数做为 value 的 object , 合并成一个最终的 reducer 函数 , 然后就可以对这个 reducer 调用 createStore。 合并后的 reducer 可以调用各个子 reducer , 并把他们的结果合并成一个 state 对象 。state 对象的结构由传入的多个 reducer 的 key 决定 。 代码如下(示例):
import React from 'react'
import { createStore, combineReducers } from 'redux'
function index(state = { info: '首页' }, action) {
switch (action.type) {
case 'index_edit_info':
return {
...state,
index: action.info
}
}
return state
}
function list(state = { info: '列表' }, action) {
switch (action.type) {
case 'index_edit_info':
return {
...state,
list: action.info
}
}
return state
}
let reducer = combineReducers({
index,
list
});
let store = createStore(reducer)
store.subscribe(() => {
console.log(store.getState())
})
store.dispatch({
type: 'index_edit_info',
info: '啦啦啦'
})
function App() {
return (
<div>
</div>
);
}
总结
以上就是今天要讲的内容,本文仅仅简单介绍了Redux的使用,而Redux提供了大量能使我们快速便捷地处理数据的函数和方法。
|