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

React Native 头部按钮onPress事件始终获取state变量初始值如何解决

问题根源

这是React闭包陷阱导致的:你当前写的useEffect依赖数组仅包含route和navigation,只会在组件初始化或这两个变量变更时执行一次。执行时绑定的handleSubmit是首次渲染生成的版本,它的闭包内捕获的totalExpense永远是初始值'0'。后续你更新totalExpense时,useEffect不会重新触发,头部按钮绑定的始终是旧版本的提交函数,因此无法拿到最新的state值。

修复方案

方案1:补全useEffect依赖项

将提交函数和用到的state加入依赖数组,每次相关值更新时都会重新绑定头部按钮的事件,确保拿到最新值:

// 用useCallback包裹提交函数,避免不必要的重绑定
const handleSubmit = useCallback(() => {
  console.log('total Expense', totalExpense);
}, [totalExpense]);

useEffect(() => {
  navigation.setOptions({
    headerRight: () => (
      <IconButton
        name='check'
        bgColor={colors.primary}
        onPress={handleSubmit}
      />
    ),
  });
// 补全依赖
}, [route, navigation, handleSubmit]);

方案2:用useRef同步最新state(适合依赖项较多的场景)

通过ref存储state的最新值,提交时直接从ref取值,无需修改useEffect依赖:

const [totalExpense, setTotalExpense] = useState('0');
const totalExpenseRef = useRef(totalExpense);

// 同步state到ref
useEffect(() => {
  totalExpenseRef.current = totalExpense;
}, [totalExpense]);

useEffect(() => {
  navigation.setOptions({
    headerRight: () => (
      <IconButton
        name='check'
        bgColor={colors.primary}
        onPress={handleSubmit}
      />
    ),
  });
}, [route, navigation]);

const handleSubmit = () => {
  // 从ref获取最新值
  console.log('total Expense', totalExpenseRef.current);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:06:04