【React】知识点归纳:redux
2019-01-29 19:25
92 查看
版权声明:Dream_Lees Blog未经本人允许,不得转载 https://blog.csdn.net/qq_41846861/article/details/86694398
redux 的核心 API redux 的三个核心概念 使用redux编写应用案例
redux
redux 理解
学习文档
- 英文文档: https://redux.js.org/
- 中文文档: http://www.redux.org.cn/
- Github: https://github.com/reactjs/redux
redux 是什么?
- redux 是一个独立专门用于做状态管理的 JS 库(不是 react 插件库)
- 它可以用在 react, angular, vue 等项目中, 但基本与 react 配合使用
- 作用: 集中式管理 react 应用中多个组件共享的状态
redux 工作流程
详细使用流程参考:https://www.cnblogs.com/goodjobluo/p/9077010.html
什么情况下需要使用 redux
- 总体原则: 能不用就不用, 如果不用比较吃力才考虑使用
- 某个组件的状态,需要共享
- 某个状态需要在任何地方都可以拿到
- 一个组件需要改变全局状态
- 一个组件需要改变另一个组件的状态
redux 的核心 API
createStore()
- 作用:
创建包含指定 reducer 的 store 对象 - 编码:
import {createStore} from 'redux' import counter from './reducers/counter' const store = createStore(counter)
store 对象
- 作用:
redux 库最核心的管理对象 - 它内部维护着:
state
reducer - 核心方法:
getState()
dispatch(action)
subscribe(listener) - 编码:
store.getState()
store.dispatch({type:‘INCREMENT’, number})
store.subscribe(render)
applyMiddleware()
- 作用:
应用上基于 redux 的中间件(插件库) - 编码:
import {createStore, applyMiddleware} from 'redux' import thunk from 'redux-thunk' // redux 异步中间件 const store = createStore( counter, applyMiddleware(thunk) // 应用上异步中间件 )
combineReducers()
- 作用:
合并多个 reducer 函数 - 编码:
export default combineReducers({ user, chatUser, chat })
redux 的三个核心概念
action
- 标识要执行行为的对象
- 包含 2 个方面的属性
a. type: 标识属性, 值为字符串, 唯一, 必要属性
b. xxx: 数据属性, 值类型任意, 可选属性 - 例子:
const action = { type: 'INCREMENT', data: 2 }
- Action Creator(创建 Action 的工厂函数)
const increment = (number) => ({type: 'INCREMENT', data: number})
reducer
- 根据老的 state 和 action, 产生新的 state 的纯函数
- 样例
export default function counter(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + action.data case 'DECREMENT': return state - action.data default: return state } }
- 注意
a. 返回一个新的状态
b. 不要修改原来的状态
store
- 将 state,action 与 reducer 联系在一起的对象
- 如何得到此对象?
import {createStore} from 'redux' import reducer from './reducers' const store = createStore(reducer)
- 此对象的功能?
getState(): 得到 state
dispatch(action): 分发 action, 触发 reducer 调用, 产生新的 state
subscribe(listener): 注册监听, 当产生了新的 state 时, 自动调用
使用redux编写应用案例
相关文章推荐
- 【React】知识点归纳:使用redux来编写一个简单的应用
- 【React】知识点归纳:redux 异步编程
- 【服务端知识点】(十五天)文件上传实现——30天node+mongo+react+redux+express搭建完美资源后台管理系统+前端(全栈工程师 结合antd)
- 【React】知识点归纳:纯函数和高阶函数
- 基于react、react-redux的加减计数器
- react-redux使用实例
- React第三方组件5(状态管理之Redux的使用④TodoList下)
- React 数据流管理架构之 Redux
- 在react-native中使用redux
- 使用Redux管理你的React应用
- Redux状态管理 2.Redux如何和React一起使用
- javaEE基础篇,day0:知识点归纳
- React和Redux的连接react-redux
- 为什么 react 中要使用 redux
- 金融相关知识点的归纳
- react、redux个人学习笔记
- react state or redux store?
- react-router-redux
- 动态链接库知识点归纳之一(DLL概念,如何建立,如何使用,如何优化,如何查看)
- java知识点归纳