zoukankan      html  css  js  c++  java
  • Redux:store

    Store是一个对象。他有如下职责:

    1.存放state

    2.对外提供访问state的接口: getState()

    3.允许state更新:dispatch(action)

    4.注册监听器: subscribe(listener)

    5.注销监听器,通过subscribe返回的函数

    redux所在的应用只能有一个store实例,如果想将state操作分解成多个逻辑,只能将Reducer的代码分解为多个部分,以函数调用的方式提取出来处理各自的逻辑。

    当我们已经有一个处理state的Reducer函数时,比如todoApp,创建store实例非常简单,只需将它传入createStore():

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

    createStore()可以接收第二个参数,作为state的初始值。文档中提到的一种情况是传入服务器返回的state作为初始state,实现定制化。

    Dispatching Actions:

     1 //action creators
     2 import {
     3   addTodo,
     4   toggleTodo,
     5   setVisibilityFilter,
     6   VisibilityFilters
     7 } from './actions'
     8 
     9 // Log the initial state
    10 console.log(store.getState())
    11 
    12 // Every time the state changes, log it
    13 // Note that subscribe() returns a function for unregistering the listener
    14 let unsubscribe = store.subscribe(() =>
    15   console.log(store.getState())
    16 )
    17 
    18 // Dispatch some actions
    19 store.dispatch(addTodo('Learn about actions'))
    20 store.dispatch(addTodo('Learn about reducers'))
    21 store.dispatch(addTodo('Learn about store'))
    22 store.dispatch(toggleTodo(0))
    23 store.dispatch(toggleTodo(1))
    24 store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED))
    25 
    26 // Stop listening to state updates
    27 unsubscribe()

    一开始我以为store是一个独立且区别于reducer的对象,现在发现,原来createStore只是对Reducer做了一层包装。

    当store.dispatch()方法被调用的时候,只需要传入action,其内部会自动获取即刻的state并一起传入Reducer中。

    值得一提的是,subscribe()方法默认订阅的是state发生变化这个事件,和所有基于事件机制的方法一样,传入的是一个callback。其返回值默认是一个注销subscribe()的函数。

  • 相关阅读:
    腾讯视频插入网页的代码;
    FW: 软件持续交付的诉求;
    TOGAF
    Windows WSL2 htop打开黑屏的问题解决
    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='appts.xxx.com%20', port=443):
    sqlalchemy实现模糊查询
    jenkins过滤版本,可选择版本
    QML 布局之一:锚布局详解(各种例子)
    Qt Quick 常用控件:Button(按钮)用法及自定义
    The Common Order Operations of Dis Operation System (DOSS)
  • 原文地址:https://www.cnblogs.com/alan2kat/p/7501093.html
Copyright © 2011-2022 走看看