Redux

作者: 一刀一个小黄鱼 | 来源:发表于2018-11-15 01:25 被阅读6次

创建counter方法,state(初始值),action(触发的动作)

const counter = (state = 0, action = {}) => {
    switch(action.type) {
        case 'INCREMENT':
            return state + 1;
        default: return state;
    }
}

export default counter;

引入 createStore from redux

import { createStore } from 'redux';
const store  = createStore(reducer);

const render = () => {
    ReactDOM.render(
        <App
            value={ store.getState() }
            onClick={ () => store.dispatch({ type: 'INCREMENT' })}
        />, document.getElementById('root')
    );
}

render();

store.subscribe(); //监听store发生变化
store.getState() // 获取state
store.dispatch // 更新state

React-redux

connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])
const mapStateToProps = (store) => {
  return {
      counter: store.counter
  }
}

// 将 store 中的数据作为 props 绑定到组件上。

cosnt mapDispatchToProps = (dispatch) => {
  return {
    add: dispatch({ type: 'add' })
  }
}

// 将 action 作为 props 绑定到组件上

相关文章

网友评论

      本文标题:Redux

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