Hox 状态更新后组件为什么不重新渲染?

海霞 Dev 阅读 20

我用 Hox 写了个简单的计数器,但点击按钮后状态变了,页面却没更新。是不是我哪里写错了?

我试过把 store 单独抽出来,也确认了 dispatch 被调用了,控制台打印的值是对的,就是 UI 不刷新。

import { create } from 'hox'
import { useState } from 'react'

const useCounter = () => {
  const [count, setCount] = useState(0)
  const increment = () => setCount(count + 1)
  return { count, increment }
}

export const useCounterStore = create(useCounter)

// 在组件里
const App = () => {
  const { count, increment } = useCounterStore()
  return <button onClick={increment}>{count}</button>
}
我来解答 赞 3 收藏
二维码
手机扫码查看
1 条解答
UX-一然
UX-一然 Lv1
闭包陷阱,老问题了。increment 函数里直接用 count,拿的是旧值,改成函数式更新就行了。

const increment = () => setCount(prev => prev + 1)


以后遇到这种"状态变了但UI不动"的情况,先检查是不是闭包抓了旧值,用函数式更新能避开大部分这种坑。
点赞 1
2026-03-01 09:00