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

ContextProvider中使用useState修改新值时出现1-2秒延迟求助

问题:React Native Context中修改State新值时出现2秒延迟

我在组件外层包裹了ContextProvider,并为其关联了useState钩子。当在子组件中调用set方法修改该useState的值时,若设置的是与当前状态相同的值则无延迟,若设置新值则会出现2秒左右的延迟。

已做的调试排查

  • 延迟并非由数值计算导致,设置随机值(如当前时间戳)仍会出现延迟
  • 移除useCallback无影响
  • 组件重渲染不是延迟原因,无组件使用该Context
  • 使用useMemo缓存状态变量也无法解决延迟

项目配置

React-native: 0.70.6

代码示例

ContextProvider代码

import React from 'react';

type CurrentEntryContextType = {
  answersBeingSaved: number;
  setAnswersBeingSaved: (count: number) => void;
};

export const CurrentEntryContext = React.createContext<CurrentEntryContextType>({
  answersBeingSaved: 5,
  setAnswersBeingSaved: () => {},
});

主组件代码

function App() {
  const [answersBeingSaved, setAnswersBeingSaved] = useState<number>(5);
  const currentEntryContext = useMemo(() => {
    return {
      answersBeingSaved: answersBeingSaved,
      setAnswersBeingSaved: setAnswersBeingSaved,
    };
  }, [answersBeingSaved]);
  return (
    <>
      <CurrentEntryContext.Provider value={currentEntryContext}>
              <MainNavigationBar />
      </CurrentEntryContext.Provider>
    </>
  );
}

存在2秒延迟的修改组件

function RandomComponent() {
  const currentEntryContext = useContext(CurrentEntryContext);
  
  const acknowledgeAnswerBeingSaved = useCallback(() => {
    currentEntryContext.setAnswersBeingSaved(
      currentEntryContext.answersBeingSaved + 3
    );
  }, [currentEntryContext]);
  return <></>;
}

无延迟的修改组件(仅设置固定值5)

function RandomComponent() {
  const currentEntryContext = useContext(CurrentEntryContext);
  
  const acknowledgeAnswerBeingSaved = useCallback(() => {
    const redundantVariable = currentEntryContext.answersBeingSaved + 3;
    currentEntryContext.setAnswersBeingSaved(
      5
    );
  }, [currentEntryContext]);
  return <></>;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:45:48