Skip to content
⚠️ This article was written in 2021. Some content may be outdated.

Jotai 原子化狀態管理

在日常開發中,Jotai 原子化狀態管理的使用頻率越來越高。本文系統地講解其用法、原理和最佳化策略。

快速上手

在這個基礎上,我們可以進一步最佳化:

javascript
import { useReducer, useCallback } from 'react'

const initialState = { items: [], filter: '', sort: 'date' }

function reducer(state, action) {
  switch (action.type) {
    case 'SET_ITEMS': return { ...state, items: action.payload }
    case 'SET_FILTER': return { ...state, filter: action.payload }
    case 'ADD_ITEM': return { ...state, items: [...state.items, action.payload] }
    case 'REMOVE_ITEM': return { ...state, items: state.items.filter(i => i.id !== action.payload) }
    default: throw new Error(`Unknown: ${action.type}`)
  }
}

這種模式在大型專案中非常實用,能顯著降低維護成本。

內部原理

實際專案中的用法會更復雜一些:

javascript
'use client'
import { useChat } from 'ai/react'

export function AIChat() {
  const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
    api: '/api/chat'
  })
  return (
    <div className="chat-container">
      {messages.map(m => (
        <div key={m.id} className={`message ${m.role}`}>
          <p>{m.content}</p>
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button type="submit" disabled={isLoading}>傳送</button>
      </form>
    </div>
  )
}

通過這種方式,程式碼的可測試性和可擴充套件性都得到了提升。

業務實戰

以下是一個完整的示例:

javascript
import { useReducer, useCallback } from 'react'

const initialState = { items: [], filter: '', sort: 'date' }

function reducer(state, action) {
  switch (action.type) {
    case 'SET_ITEMS': return { ...state, items: action.payload }
    case 'SET_FILTER': return { ...state, filter: action.payload }
    case 'ADD_ITEM': return { ...state, items: [...state.items, action.payload] }
    case 'REMOVE_ITEM': return { ...state, items: state.items.filter(i => i.id !== action.payload) }
    default: throw new Error(`Unknown: ${action.type}`)
  }
}

注意邊界條件處理,這在生產環境中至關重要。

效能對比

關鍵在於理解核心邏輯:

javascript
'use client'
import { useChat } from 'ai/react'

export function AIChat() {
  const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
    api: '/api/chat'
  })
  return (
    <div className="chat-container">
      {messages.map(m => (
        <div key={m.id} className={`message ${m.role}`}>
          <p>{m.content}</p>
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button type="submit" disabled={isLoading}>傳送</button>
      </form>
    </div>
  )
}

效能最佳化需要結合具體場景,不是所有情況都需要過度最佳化。

問題排查

我們可以通過以下方式來改進:

javascript
import { useReducer, useCallback } from 'react'

const initialState = { items: [], filter: '', sort: 'date' }

function reducer(state, action) {
  switch (action.type) {
    case 'SET_ITEMS': return { ...state, items: action.payload }
    case 'SET_FILTER': return { ...state, filter: action.payload }
    case 'ADD_ITEM': return { ...state, items: [...state.items, action.payload] }
    case 'REMOVE_ITEM': return { ...state, items: state.items.filter(i => i.id !== action.payload) }
    default: throw new Error(`Unknown: ${action.type}`)
  }
}

這套方案已經在線上穩定運行了半年以上,經過了實際驗證。

小結

  • 關注社群動態,技術方案需要持續迭代
  • 不要為了用新技術而用新技術
  • 程式碼示例僅供參考,需根據業務場景調整
  • Jotai 原子化狀態管理不是銀彈,需要根據專案規模和技術棧選擇

MIT Licensed