react-redux 配合ramda实现计数器

react-redux  配合ramda实现计数器

https://react-redux.js.org/

安装

yarn add react-redux

 

配合ramda实现的计数器

import React from "react";
import { createStore } from "redux";
import { Provider, useSelector } from "react-redux";
import km from "keymirror";
import * as R from "ramda";

const ACTION_TYPES = km({
  INC: null,
  DEC: null,
  RESET: null,
  INC_DOUBLE: null,
});

const initState = {
  count: 0,
};

const reducer = (state = initState, action, pyload) => {
  switch (action.type) {
    case ACTION_TYPES.INC:
      return R.evolve({ count: R.inc }, state);
    case ACTION_TYPES.DEC:
      return R.evolve({ count: R.dec }, state);
    case ACTION_TYPES.INC_DOUBLE:
      return R.evolve({ count: R.add(action.dx) }, state);
    default:
      return state;
  }
};

const store = createStore(reducer, initState);

const Counter = () => {
  const inc = () => {
    store.dispatch({ type: ACTION_TYPES.INC, dx: 1 });
  };
  const dec = () => {
    store.dispatch({ type: ACTION_TYPES.DEC, dx: 1 });
  };

  const incDouble = () => {
    store.dispatch({ type: ACTION_TYPES.INC_DOUBLE, dx: 2 });
  };
  const count = useSelector(R.path(["count"]));

  return (
    <div>
      <div>count:{count}</div>
      <button onClick={inc}>inc</button>
      <button onClick={dec}>dec</button>
      <button onClick={incDouble}>incDouble</button>
    </div>
  );
};
export default () => {
  return (
    <Provider store={store}>
      <Counter></Counter>
    </Provider>
  );
};

 

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » react-redux 配合ramda实现计数器