react hook + stamen store + pug实现纯函数无痛版react开发体验

941 阅读1分钟

基于最新的react 16.7.0-alpha.2,结合react hook + stamen store + pug,实现纯函数无痛版react开发体验,畅快度直逼clojurescript + reagent。

看图:

import React, { useState, useEffect} from "react"
import { createStore } from "stamen"
import logo from './logo.svg'
import './App.css'

// main
function App() {
  return pug`
    div 
      //- Click Component使用组件内部state,基于hook
      UIClickUseState(showGreeting, name="xjp")
      //- Click Component使用组件外部store,基于stamen
      UIClickUseStore
`;}

// store
const Store = createStore({
  state: {
    count: 10
  },
  reducers: {
    increment(state) {
      state.count++;
    },
    decrement(state) {
      state.count--;
    }
  },
  effects: {
    async asyncIncrement(dispatch) {
      await new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, 1000)
      })
      dispatch("increment")
    }
  }
});

// UIClickUseState
function UIClickUseState(props) {
  const [count, setCount] = useState(0);
  const addNum = num => setCount(count + num);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
  return pug`
    div.w1.m1.flex
      if props.showGreeting
        p.greeting Hello #{props.name}!
      button(
        onClick=()=>addNum(10)
      ) #{count} Click Me
`;
}

// UIClickUseStore
function UIClickUseStore(props) {
  const { get, dispatch } = Store.useStore();
  const count = get(s => s.count);
  return pug`
    div
      span #{count}
      button(onClick=()=>dispatch('decrement')) -
      button(onClick=()=>dispatch('increment')) +
      button(onClick=()=>dispatch('asyncIncrement')) +
`;
}

export default App