美文网首页
搭建一个redux风格的 store

搭建一个redux风格的 store

作者: 隐号骑士 | 来源:发表于2018-12-10 00:16 被阅读7次

上一篇文章 我们已经实现了 context, 实现了简易的多层次组件共享状态。

  • 问题: context 中的状态的更新不是受控的 / 操作不便

class App extends Component {
  constructor() {
    super()
    this.state = {
      count: 100
    }
  }

  getChildContext() {
    return {  
        count: this.state.count
    }
  }
  render(){
      ...
  }
}

  • 状态管理容器

创建 store.js


function createStore(reducer) {
    let state = null; //初始化state
    let listeners = []; //监听变化的回调函数队列
    let subscribe = (listener) => listeners.push(listener); // 定义并随后暴露添加绑定回调函数的方法
    let getState = () => state;// 定义并暴露获取读取 state 的唯一方法
    let dispatch = (action) => {
        state = reducer(state, action);//根据action改变状态
        listeners.forEach((listener) => listener())//把listeners都执行一次
    }
    dispatch({})
    return { subscribe, getState, dispatch }
}

// 改变状态的规则函数
function reducer(state, action) {
    if (!state) {
        state = {
            number: 1
        }
    }
    switch (action.type) {
        case 'AddNumber':
            state.number++;
            break;
        case 'MinusNumber':
            state.number--;
            break;
        default:
    }
    return { ...state }
}

export const store = createStore(reducer)
  • 在最外层组件中
import { store } from './store';

class App extends Component {
// ...
  getChildContext() {
    return { store }
  }

  static childContextTypes = {
    store: PropTypes.object,
  }
//...
}
  • 任意在子组件中
class ChildComponent extends Component {
    constructor() {
        super()
        this.state = {}
    }
    //...
    componentDidMount() {
        const { store } = this.context
        this._updateState()
        store.subscribe(() => this._updateState()) // 添加dispatch的回调函数,自动更新最新的数据
    }

    _updateState() {
        const { store } = this.context;
        const state = store.getState();
        this.setState(state)
    }

    render(){
        //...
    }
}

如此一来, 所有关于store的状态更新必然通过dispatch,做到了受控的状态更新

相关文章

  • 搭建一个redux风格的 store

    上一篇文章 我们已经实现了 context, 实现了简易的多层次组件共享状态。 问题: context 中的状态的...

  • react-redux的使用

    redux管理状态环境搭建 store.js reducer.js actions.js 详情图

  • redux学习笔记

    什么是redux架构 //首先我们应该认识redux的核心store,store直译过来就是仓库,redux概念中...

  • redux

    redux原理 实现一个store;

  • 如何快速理解使用redux

    使用redux的主要流程 首先 引入 redux 使用redux中的createStore去创建一个store 在...

  • vuex、redux、react-redux、react hoo

    redux (观察者模式) react-redux 1、创建reducer 2、 store store 提供外界...

  • Redux

    Redux = Reducer + Flux Redux示例 ./store/index.js ./redux/t...

  • 浅入 Redux

    Redux 三大核心 Redux的核心由三部分组成:Store, Action, Reducer。 Store :...

  • react学习第一阶段总结

    redux重要概念 第一阶段总结 web是一个状态机。 redux中有一个store,store保存了所有状态。 ...

  • redux 笔记

    Store Store 就是保存数据的地方。 可以看作是一个容器。 整个应用只能有一个 Store。 Redux ...

网友评论

      本文标题:搭建一个redux风格的 store

      本文链接:https://www.haomeiwen.com/subject/ceulhqtx.html