1. 程式人生 > >我理想中的狀態管理工具

我理想中的狀態管理工具

現已存在許多成熟的狀態管理解決方案:Redux、Mobx、Mobx-state-tree,還有基於 Redux 的 Dva.js、Rematch... 但對於我個人來說,理想的狀態管理工具只需同時滿足兩個特點:

  • 簡單易用,並且適合中大型專案
  • 完美地支援 Typescript

要做到這兩點其實並不簡單。

首先說說 “簡單易用,並且適合中大型專案”,這裡包含層含義:

  • Api 足夠簡單,儘量引入少的概念
  • 易用性高,使用者易用上手,較少的冗餘程式碼
  • 能讓使用者更容易的寫出可維護性高的程式碼
  • 能讓業務程式碼有良好地組織方式

怎麼才能算是簡單易用呢?用一個叫

reworm 的狀態管理庫來舉例,它的使用方式是這樣的:

import React from 'react';
import { Provider, create } from 'reworm';

const { set, get } = create({ name: 'John' });

class App extends React.Component {
  componentDidMount() {
    set(prev => ({ name: 'Peter' + prev.name }));
  }
  render() {
    return (
      <Provider
>
<div>{get(s => s.name)}</div> </Provider>
); } } 複製程式碼

我碰巧寫寫過一個類似狀態管理庫,叫 mistate,甚至更簡單,連 Provider 都不用,實現程式碼也只有 40 行。用法如下:

import React from 'react';
import { create } from 'mistate';

const { get, set } = create({ count: 0 });

const App = () => (
  <div
>
<span>{get(s => s.text)}</span> <button onClick={() => set(prev => ({ count: prev.count++ }))}>+</button> </div>
); 複製程式碼

它們足夠簡單,非常容易上手,但是它們致命是缺點是並不適合中大型專案,它們自由度太高,缺乏對業務程式碼的約束,在多人合作的中大型專案,程式碼的可維護性會大大降低,因為每個人寫的程式碼風格可能都不一樣。舉個例子,有些人可能會直接在 Component 中使用 set,有些人可能會基於 set 封裝成一個個 acton:

import React from 'react';
import { create } from 'mistate';

const { get, set } = create({ count: 0 });
const actions = {
  increment() {
    set(prev => ({ count: prev.count++ })
  },
  decrement() {
    set(prev => ({ count: prev.count-- })
  },
}

const App = () => (
  <div>
    <span>{get(s => s.text)}</span>
    <button onClick={() => actions.increment)}>+</button>
    <button onClick={() => actions.decrement)}>+</button>
  </div>
);
複製程式碼

這種自由度雖然靈活度高,但是降低了程式碼的可維護性。

另外,用 render props 獲取 state 看似比 Redux 的 Connect 簡單,但其實並不優雅,比如一個很常見的獲取多個 state,使用 render props 可能要這樣:

const Counter = create({ count: 0 });
const User = create({ name: 'foo' });
const Todo = create({ todos: [] });

const App = () => (
  <div>
    {User.get(user => (
      <div>
        <span>{user.name}</span>
        <div>
          {Todo.get(todo => (
            <div>
              {todo.todos.map(item => {
                <div>
                  <span>{item.name}</span>;
                  <span>{Counter.get(s => s.count)}</span>
                </div>;
              })}
            </div>
          ))}
        </div>
      </div>
    ))}
  </div>
);
複製程式碼

多個 render props 的巢狀會導致 callback hell 類似結果,直接讓你的程式碼反人類。

上面說完了 “簡單易用”,下面聊聊 “適合中大型專案”。當然,我心目中的 “適合中大型專案” 的前提是 “簡單易用”,否者我並不會選擇它。

首先上面面說的 reworm 和 mistate 並不適合在中大型專案中使用,他們適合用在小型專案,比如一個簡單的營銷活動,還以非常適合的場景就是在工具類庫中使用,因為它們足夠簡單、輕量。

再說說大家熟悉 Redux 和 Mobx,首先是 Redux ,我個人認為 Redux 確實滿足 “適合中大型專案”,因為使用者幾乎都會按照它推薦的方式來組織程式碼,但它不滿足 “簡單易用”,太過於繁瑣,使用起來有種吃*的感覺(本人沒吃過~)。然後是 Mobx,個人挺喜歡,挺 “簡單易用”,對使用者寫出的程式碼有一定的限制,但感覺又太過於自由,並且非 Immutable,給人感覺是一個很中庸的解決方案。

在滿足 “簡單易用,並且適合中大型專案” 的前提下,個人比較喜歡的狀態管理解決方案是: dvarematchmirror,三者都是基於 Redux 開發,他們的 Api 相似度極高,簡化了 Redux 的使用,使得程式碼組織方更加合理,通俗的說就是為 Redux 使用者提供了最舒服的套路去寫程式碼,可以說是當前 Redux 社群中的最佳實踐。

看看他們是如何組織程式碼,以 mirror 來舉例:

import React from 'react'
import mirror, {actions, connect, render} from 'mirrorx'

// declare Redux state, reducers and actions,
// all actions will be added to `actions`.
mirror.model({
  name: 'app',
  initialState: 0,
  reducers: {
    increment(state) { return state + 1 },
    decrement(state) { return state - 1 }
  },
  effects: {
    async incrementAsync() {
      await new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, 1000)
      })
      actions.app.increment()
    }
  }
})

// connect state with component
const App = connect(state => {
  return {count: state.app}
})(props => (
    <div>
      <h1>{props.count}</h1>
      {/* dispatch the actions */}
      <button onClick={() => actions.app.decrement()}>-</button>
      <button onClick={() => actions.app.increment()}>+</button>
      {/* dispatch the async action */}
      <button onClick={() => actions.app.incrementAsync()}>+ Async</button>
    </div>
  )
)

// start the app,`render` is an enhanced `ReactDOM.render`
render(<App />, document.getElementById('root'))
複製程式碼

可以看出它們核心是把 Redux 分散的 actions 和 reducers 合併在一個地方,並減少了樣板程式碼,而且自帶非同步 action 解決方案,抽象為 effects。

說完第一個特點,接下來是第二個特點:“完美地支援 Typescript”

為什麼我這麼這麼執著於 Typescript,使用過 Typescript 的都應該知道,不過什麼規模的專案,開發體驗比使用 Javascript 好太多,沒入坑的同學可以去試試。

基於第一特點的篩選,原生 Redux 和 Mobx 已被忽略,對於dvarematchmirror,對 Typescript 支援最好的是 Rematch,它本身也是用 Typescript 寫的,遂繼續忽略 Dva 和 mirror。

在聊 Rematch 和 Typescript 一起使用之前,先了解一下原生 Redux 和 Typescript 怎麼一起使用, 用使用頻率最高的 connect 舉個例子:

interface StateProps {
  count: number
}

interface DispatchProps {
  increment: () => void
}

interface OwnProps {
  name: string
}

export default connect<StateProps, DispatchProps, OwnProps>(
    mapStateToProps,
    mapDispatchToProps
)(MyComponent);
複製程式碼

為了 MyComponent 的 props 能有正確的型別斷言,你必須手寫 StateProps 和 DispatchProps,這是一件很蛋疼的事情,也沒有體現出使用 Typescript 的優勢所在。理想的應該是 connect 之後 MyComponent 的 props 能被自動推倒出來,這才是完美的開發體驗。但是基於 hoc 的使用方式,這方面貌似暫時無解,除非使用 render props,但是 render props 的書寫方式真是有點辣眼睛。

再來看看 Rematch 和 Typescript 怎麼一起使用:

import * as React from 'react'
import { connect } from 'react-redux'

import { iRootState, Dispatch } from './store'

const mapState = (state: iRootState) => ({
	dolphins: state.dolphins,
	sharks: state.sharks,
})

const mapDispatch = (dispatch: Dispatch) => ({
	incrementDolphins: dispatch.dolphins.increment,
	incrementDolphinsAsync: dispatch.dolphins.incrementAsync,
	incrementSharks: () => dispatch.sharks.increment(1),
	incrementSharksAsync: () => dispatch.sharks.incrementAsync(1),
	incrementSharksAsync2: () => dispatch({ type: 'sharks/incrementAsync', payload: 2 }),
})

type connectedProps = ReturnType<typeof mapState> & ReturnType<typeof mapDispatch>
type Props = connectedProps

class Count extends React.Component<Props> {
  // ....
}

export default connect(mapState, mapDispatch)(Count)

複製程式碼

跟原生的 Redux 基本大同小異,沒體現 Typescript 的優勢,有點強行上 Typescript 的感覺。

對我個人而言 Rematch 也無法滿足這兩個特點。

所以, 我決定自己造一個:

stamen: 可能是基於 Hooks 和 Typescript 最好的狀態管理工具