饥人谷技术博客代码森林React.js学习

初识Redux中的Action, Reducer, Store

2018-08-23  本文已影响0人  Apolo_Du

Redux 是什么

Redux 是一个 JavaScript 状态容器,提供可预测化的状态管理

state, store 和 action

示意图:

redux的工作流程

初始化 Redux

npm install --save redux

// 安装react 支持

npm install --save react-redux

npm install --save-dev redux-devtools

Redux 中的 action, reducer 和 store

创建一个初始 state

const initialState = {
  count: 0
};

action

// create actions
const ADD_ACTION = "ADD";
const REDUCE_ACTION = "REDUCE";

const add = num => {
  return {
    type: ADD_ACTION,
    num
  };
};

const reduce = num => {
  return {
    type: REDUCE_ACTION,
      num
  };
}; 

reducer ( 状态处理函数 ) :

const reducer = (state = initialState, action) => {
  switch (action.type) { 
      case "ADD": 
        return Object.assign({}, state, { 
            count: state.count + action.num 
        }); 

      case "REDUCE": 
        return Object.assign({}, state, { 
            count: state.count - action.num 
         }); 

      default: 
         return state;
    }
};

store 对象: state状态管理器

const reduxStore = createStore(reducer); 

store 对象 API

store.dispatch(action)
store.getState();

redux 工作流程

action, Reducer, store 之间的关系

const { createStore } = Redux
let action = {type: 'yyy'}
const reducer = (state, action) => { xxxxx }
const store =  createStore(reducer)

示例代码:

点击这里运行示例代码

import React from "react";
import ReactDOM from "react-dom";
import Redux, {createStore} from "redux";

// create actions
const ADD_ACTION = "ADD";
const REDUCE_ACTION = "REDUCE";

const add = num => {
  return {
    type: ADD_ACTION,
    num
  };
};

const reduce = num => {
  return {
    type: REDUCE_ACTION,
    num
  };
};

// initialize a state
const initialState = {
  count: 0
};

// create a reducer
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "ADD":
      return Object.assign({}, state, {
        count: state.count + action.num
      });

    case "REDUCE":
      return Object.assign({}, state, {
        count: state.count - action.num
      });

    default:
      return state;
  }
};

function getCurrentState() {
  return reduxStore.getState();
}

function addState() {
  reduxStore.dispatch(add(1));
  console.log(getCurrentState());
}

function reduceState() {
  reduxStore.dispatch(reduce(1));
  console.log(getCurrentState());
}

const reduxStore = createStore(reducer);
console.log(reduxStore.getState());

class App extends React.Component {
  constructor(props) {
    super(props);
    //初始化 state
    this.state = getCurrentState();
  }

  render() {
    return (
      <div>
        <h1>A Redux Example, open console to check results.</h1>
        <button onClick={addState}>add</button>
        <button onClick={reduceState}>reduce</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App/>, rootElement);

参考和quickstart

上一篇下一篇

猜你喜欢

热点阅读