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

如何使用router.navigate()传递嵌套对象数组(Expo Router)

解决expo-router传递嵌套对象数组的问题

问题原因

expo-router的导航参数默认会被序列化为URL兼容格式,嵌套对象数组无法被正确序列化,导致接收时呈现为[object Object]。

解决方案

方案1:JSON序列化/反序列化传递

跳转前将对象转为JSON字符串,接收页面再解析回原对象:

  • 跳转页面代码:
import { router } from 'expo-router';

const handleNavigate = () => {
  const serializedItem = JSON.stringify(item);
  router.navigate({
    pathname: 'path/to/screen',
    params: { item: serializedItem }
  });
};
  • 目标页面接收代码:
import { useLocalSearchParams } from 'expo-router';

const TargetScreen = () => {
  const { item } = useLocalSearchParams();
  const parsedItem = item ? JSON.parse(item) : null;

  // 此时可正常访问parsedItem.nestedObjectArray
  return (
    // 页面内容
  );
};

方案2:全局状态管理

若数据复杂或需多页面共享,推荐用状态管理工具(如Zustand、React Context):

以Zustand为例:

  1. 安装依赖:npm install zustand
  2. 创建状态存储:
// stores/itemStore.js
import { create } from 'zustand';

export const useItemStore = create((set) => ({
  currentItem: null,
  setCurrentItem: (item) => set({ currentItem: item })
}));
  1. 跳转前存入状态:
import { useItemStore } from '../stores/itemStore';
import { router } from 'expo-router';

const handleNavigate = () => {
  const setCurrentItem = useItemStore(state => state.setCurrentItem);
  setCurrentItem(item);
  router.navigate('path/to/screen');
};
  1. 目标页面读取状态:
import { useItemStore } from '../stores/itemStore';

const TargetScreen = () => {
  const currentItem = useItemStore(state => state.currentItem);

  // 直接使用currentItem,嵌套数组可正常访问
  return (
    // 页面内容
  );
};

注意事项

  • 方案1适合一次性传值,但对象过大可能触发平台URL长度限制。
  • 方案2更适配复杂数据场景,无需担心序列化问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:59:53