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

Expo路由传参问题:返回后再次跳转报URI组件格式错误

问题解决:返回搜索页后点击结果报URI格式错误

问题根源

你遇到的问题是因为查询参数未完全编码,或返回页面后参数被二次编码导致的。比如你仅对name做了编码,但macros直接将JSON.stringify的结果拼入URL,其中可能包含特殊字符;另外返回/search页后,若组件状态保留了已编码的参数值,再次点击时会重复编码,最终触发malformed URIcomponent错误。

正确解决方案

方案1:用路由对象形式自动编码(推荐)

无需手动拼接URL字符串,直接给router.push传入路由对象,框架会自动对所有查询参数完成URI编码,彻底避免手动编码遗漏或重复编码的问题:

<Pressable
  onPress={() =>
    router.push({
      pathname: '/recipe',
      query: {
        id,
        name,
        brandName,
        macros: JSON.stringify(macros)
      }
    })
  }
>

方案2:手动对所有参数编码

如果必须手动拼接URL,要确保每个查询参数都经过encodeURIComponent处理,包括id、brandName和macros的序列化结果:

const encodedId = encodeURIComponent(id);
const encodedName = encodeURIComponent(name);
const encodedBrandName = encodeURIComponent(brandName);
const encodedMacros = encodeURIComponent(JSON.stringify(macros));

<Pressable
  onPress={() =>
    router.push(
      `/recipe?id=${encodedId}&name=${encodedName}&brandName=${encodedBrandName}&macros=${encodedMacros}`
    )
  }
>

额外注意点

  • 确保/search页面的组件状态中,存储的是原始未编码的参数值,不要将编码后的值存入状态,避免返回后再次点击时重复编码。
  • 避免直接把JSON.stringify(recipe)这类复杂对象拼入URL,拆分参数更易维护,也能减少特殊字符的出现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:02:45