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

React Native中navigation.navigate路由参数正确但数据未更新求助

解决React Native导航跳转后页面数据不更新问题

问题出在你的useEffect依赖配置上:

useEffect(() => {
  fetch(`https://.....&qid=${qid}`)
  .then(response => response.json())
  .then(json => setQuestionData(json))
}, []); 

空数组[]作为依赖,会让这个副作用只在组件首次挂载时执行一次。当你通过navigation.navigate传递新的qid参数时,组件不会重新触发API请求,所以页面依然展示旧数据;而刷新页面会重新挂载组件,此时读取到新的qid,自然能请求到正确数据。

修复方案

把qid添加到useEffect的依赖数组中,这样每当qid发生变化时,就会重新执行API请求,获取对应的数据:

useEffect(() => {
  fetch(`https://.....&qid=${qid}`)
  .then(response => response.json())
  .then(json => setQuestionData(json))
}, [qid]); // 这里添加qid作为依赖

额外建议

  • 如果API请求还依赖其他参数(比如userid),当这些参数变化也需要重新请求时,也要把它们加入依赖数组
  • 可以添加加载状态和错误捕获逻辑,避免数据加载过程中页面空白或出现未处理的错误:
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
  setLoading(true);
  setError(null);
  fetch(`https://.....&qid=${qid}`)
  .then(response => {
    if (!response.ok) throw new Error('请求失败');
    return response.json();
  })
  .then(json => setQuestionData(json))
  .catch(err => setError(err.message))
  .finally(() => setLoading(false));
}, [qid]); 

内容的提问来源于stack exchange,提问作者Hayri Özcan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:25:15