react hook + stamen store + pug實現純函式無痛版react開發體驗

freemem發表於2018-11-15

基於最新的react 16.7.0-alpha.2,結合react hook + stamen store + pug,實現純函式無痛版react開發體驗,暢快度直逼clojurescript + reagent。

看圖:

react hook + stamen store + pug實現純函式無痛版react開發體驗

react hook + stamen store + pug實現純函式無痛版react開發體驗

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

複製程式碼

相關文章