你們好,這裏是吸管(⊙o⊙)… 前幾個月一直忙於c站(clicli彈幕網)的業務邏輯,因此幾乎消失了 而後,直到前幾天,react-hooks 出來後,才更新了 smoxjavascript
react-hooks 的使用我就很少說啦,有其餘文章vue
其實若是算到 smox 上,也就是狀態管理,有波動的 API 就是 useReducer
了java
const [state, dispatch] = useReducer(reducer,state)
複製代碼
能夠看到返回一個數組,咱們來試着實現它:react
export const useReducer = (initState, reducer) => {
const [state, setState] = useState(initState)
const dispatch = (action, payload) => {
let newState = reducer(state, action)
if (newState !== state) {
setState(newState)
}
}
return [state, dispatch]
}
複製代碼
沒錯,短短几行,搞定了這個 API,連源碼都不用看(⊙o⊙)… 而後 smox 也是這個道理,對比 useReducer
,smox 也對應實現了 useSmox
,以下:git
import React from 'react'
import { useSmox } from 'smox'
const mutations = {
change(state) {
state.sex = state.sex === 'boy' ? 'girl' : 'boy'
}
}
const actions = {
asyncChange({ commit }, payload) {
setTimeout(() => {
commit('change', payload)
}, 1000)
}
}
const state = {
sex: 'boy'
}
export const Sex = () => {
const [state, commit, dispatch] = useSmox(state, mutations, actions)
return (
<div> <h1>{state.sex}</h1> <button onClick={() => commit('change')}>變性</button> <button onClick={() => dispatch('asyncChange')}>異步變性</button> </div>
)
}
複製代碼
實現這個 API 的同時,smox 仍然提供了 vuex 的代碼體驗和 proxy,並且還支持 model 機制的拆分github
固然,仍是沒用多少行代碼√vuex
此次 smox 針對 react-hooks 的更新,能夠預見的是,未來將會出現 function 組件和 class 組件兩派,而且後者會被前者滿滿取代。 將來將會出現大量的 useXxx 來拓展組件數組
最後奉上 smox 的 github 地址::>_<:: 老鐵們!還差八顆星星啦!異步
歡迎試用與 star !