You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native自定义Hook中useState忽略传入初始状态问题求助

useState 未使用新传入的初始值,缓存了之前的状态(React Native + Realm)

我搞不懂为什么会出现这个问题,来求助大家:我写了一个自定义Hook useFeatures,代码如下:

const useFeatures = (existingFeatures: Ft[]) => {
    console.log('fts provided to state:', existingFeatures)
    const [features, setFeatures] = useState(existingFeatures)
    console.log('fts given by state:', features)

    // 其他逻辑...
}

控制台输出如下:

LOG  fts provided to state: [{"done": true, "ftName": "task", "name": "T"}]
LOG  fts given by state: [{"ftName": "number", "label": "N", "name": "", "value": 22}]

这个问题出现在不同组件渲染useFeatures的过程中——不同组件传入不同的初始features,但useState似乎缓存了之前的状态,完全没有使用新传入的初始值。我正在开发React Native应用,目前没法在项目外复现这个Bug,想问问有没有人遇到过类似情况。

我试过两种方法排查:

  • 用定时器执行第二个console.log
  • 在依赖为[features]的useEffect中执行console.log

结果都一样,还是出现异常输出。

补充信息

我通过Realm的useQuery Hook获取records:

const records = useQuery(
    RecordSchema,
    recs => recs.filtered('date == $0', strDateFmt(dayOn)),
    [dayOn],
).map(r => ({
    ...r,
    features: r.features.map(f => JSON.parse(f)),
}))

useFeatures被EditableRecord组件使用,渲染代码如下:

{records.map((record, i) => (
    <EditableRecord key={i} existingRecordId={record._id} />
))}

EditableRecord.tsx中的相关代码:

const existingRecord = useObject<RecordSchema>('Record', existingRecordId)

const { features, dispatchFeatures } = useFeatures(
    existingRecord?.features.map(f => JSON.parse(f)) || [],
)

当我多次更新dayOn(来自useState的状态)时,渲染的records会使用第一个record的features,产生如下异常日志:

LOG  fts provided to state: [{"color": "#844", "ftName": "tag", "name": "Tg"}]
LOG  fts given by state: [{"content": "Ssss", "ftName": "text", "name": "", "prompt": "P"}]
LOG  fts provided to state: [{"ftName": "number", "label": "N", "name": "", "value": 22}]
LOG  fts given by state: [{"content": "Ssss", "ftName": "text", "name": "", "prompt": "P"}]
LOG  fts provided to state: [{"done": true, "ftName": "task", "name": "T"}]
LOG  fts given by state: [{"content": "Ssss", "ftName": "text", "name": "", "prompt": "P"}]

内容的提问来源于stack exchange,提问作者jdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:23:10