您的位置:首页 > Web前端 > React

【React】知识点归纳:redux

2019-01-29 19:25 92 查看
版权声明:Dream_Lees Blog未经本人允许,不得转载 https://blog.csdn.net/qq_41846861/article/details/86694398

redux

  • redux 的核心 API
  • redux 的三个核心概念
  • 使用redux编写应用案例
  • redux 理解

    学习文档

    1. 英文文档: https://redux.js.org/
    2. 中文文档: http://www.redux.org.cn/
    3. Github: https://github.com/reactjs/redux

    redux 是什么?

    1. redux 是一个独立专门用于做状态管理的 JS 库(不是 react 插件库)
    2. 它可以用在 react, angular, vue 等项目中, 但基本与 react 配合使用
    3. 作用: 集中式管理 react 应用中多个组件共享的状态

    redux 工作流程

    详细使用流程参考:https://www.cnblogs.com/goodjobluo/p/9077010.html

    什么情况下需要使用 redux

    1. 总体原则: 能不用就不用, 如果不用比较吃力才考虑使用
    2. 某个组件的状态,需要共享
    3. 某个状态需要在任何地方都可以拿到
    4. 一个组件需要改变全局状态
    5. 一个组件需要改变另一个组件的状态

    redux 的核心 API

    createStore()

    1. 作用:
      创建包含指定 reducer 的 store 对象
    2. 编码:
    import {createStore} from 'redux'
    import counter from './reducers/counter'
    const store = createStore(counter)

    store 对象

    1. 作用:
      redux 库最核心的管理对象
    2. 它内部维护着:
      state
      reducer
    3. 核心方法:
      getState()
      dispatch(action)
      subscribe(listener)
    4. 编码:
      store.getState()
      store.dispatch({type:‘INCREMENT’, number})
      store.subscribe(render)

    applyMiddleware()

    1. 作用:
      应用上基于 redux 的中间件(插件库)
    2. 编码:
    import {createStore, applyMiddleware} from 'redux'
    import thunk from 'redux-thunk' // redux 异步中间件
    const store = createStore(
    counter, applyMiddleware(thunk) // 应用上异步中间件
    )

    combineReducers()

    1. 作用:
      合并多个 reducer 函数
    2. 编码:
    export default combineReducers({
    user, chatUser, chat
    })

    redux 的三个核心概念

    action

    1. 标识要执行行为的对象
    2. 包含 2 个方面的属性
      a. type: 标识属性, 值为字符串, 唯一, 必要属性
      b. xxx: 数据属性, 值类型任意, 可选属性
    3. 例子:
    const action = {
    type: 'INCREMENT', data: 2
    }
    1. Action Creator(创建 Action 的工厂函数)
    const increment = (number) => ({type: 'INCREMENT', data: number})

    reducer

    1. 根据老的 state 和 action, 产生新的 state 的纯函数
    2. 样例
    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
    }
    }
    1. 注意
      a. 返回一个新的状态
      b. 不要修改原来的状态

    store

    1. 将 state,action 与 reducer 联系在一起的对象
    2. 如何得到此对象?
    import {createStore} from 'redux'
    import reducer from './reducers'
    const store = createStore(reducer)
    1. 此对象的功能?
      getState(): 得到 state
      dispatch(action): 分发 action, 触发 reducer 调用, 产生新的 state
      subscribe(listener): 注册监听, 当产生了新的 state 时, 自动调用

    使用redux编写应用案例

    网址:https://www.geek-share.com/detail/2759826730.html

    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: