你们好,这里是吸管(⊙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 !