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

海霞 Dev 阅读 38

我用 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>
}
我来解答 赞 7 收藏
二维码
手机扫码查看
2 条解答
恒硕(打工版)
可能是 useCounter 里的 count 没有正确更新导致的。复制这个改一下,确保每次 increment 都能获取最新的 count 值:

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


这样 increment 会用之前的 count 值来计算新的 count,而不是直接用旧的 count。应该能解决 UI 不刷新的问题。
点赞
2026-03-23 09:13
UX-一然
UX-一然 Lv1
闭包陷阱,老问题了。increment 函数里直接用 count,拿的是旧值,改成函数式更新就行了。

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


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