zoukankan      html  css  js  c++  java
  • Redux API之creatStore

    createStore(reducer[initialState])

    创建一个 Redux store 来以存放应用中所有的 state。
    应用中应有且仅有一个 store。

    参数

    1. reducer (Function): 接收两个参数,分别是当前的 state 树和要处理的 action,返回新的 state 树。

    2. [initialState(any): 初始时的 state。 在同构应用中,你可以决定是否把服务端传来的 state 水合(hydrate)后传给它,或者从之前保存的用户会话中恢复一个传给它。如果你使用 combineReducers创建 reducer,它必须是一个普通对象,与传入的 keys 保持同样的结构。否则,你可以自由传入任何reducer 可理解的内容。

    返回值

    (Store): 保存了应用所有 state 的对象。改变 state 的惟一方法是 dispatch action。你也可以 subscribe 监听 state 的变化,然后更新 UI。

     1 import { createStore } from 'redux'
     2 
     3 function todos(state = [], action) {
     4   switch (action.type) {
     5     case 'ADD_TODO':
     6       return state.concat([ action.text ])
     7     default:
     8       return state
     9   }
    10 }
    11 
    12 let store = createStore(todos, [ 'Use Redux' ])
    13 
    14 store.dispatch({
    15   type: 'ADD_TODO',
    16   text: 'Read the docs'
    17 })
    18 
    19 console.log(store.getState())
    20 // [ 'Use Redux', 'Read the docs' ]
    View Code

    小贴士

    • 应用中不要创建多个 store!相反,使用 combineReducers 来把多个 reducer 创建成一个根 reducer。

    • 你可以决定 state 的格式。你可以使用普通对象或者 Immutable 这类的实现。如果你不知道如何做,刚开始可以使用普通对象。

    • 如果 state 是普通对象,永远不要修改它!比如,reducer 里不要使用 Object.assign(state,newData),应该使用 Object.assign({}, state, newData)。这样才不会覆盖旧的 state。也可以使用Babel 阶段 1 中的 ES7 对象的 spread 操作 特性中的 return ...state...newData }

    • 对于服务端运行的同构应用,为每一个请求创建一个 store 实例,以此让 store 相隔离。dispatch 一系列请求数据的 action 到 store 实例上,等待请求完成后再在服务端渲染应用。

    • 当 store 创建后,Redux 会 dispatch 一个 action 到 reducer 上,来用初始的 state 来填充 store。你不需要处理这个 action。但要记住,如果第一个参数也就是传入的 state 如果是 undefined 的话,reducer 应该返回初始的 state 值。

  • 相关阅读:
    English,The Da Vinci Code, Chapter 23
    python,meatobject
    English,The Da Vinci Code, Chapter 22
    English,The Da Vinci Code, Chapter 21
    English,The Da Vinci Code, Chapter 20
    English,The Da Vinci Code, Chapter 19
    python,xml,ELement Tree
    English,The Da Vinci Code, Chapter 18
    English,The Da Vinci Code, Chapter 17
    English,The Da Vinci Code, Chapter 16
  • 原文地址:https://www.cnblogs.com/ZSG-DoBestMe/p/5280109.html
Copyright © 2011-2022 走看看