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

如何通过React Router Outlet上下文传递props并按名称获取?

React Router Outlet上下文如何按名称而非顺序获取?

当前在React Router的Outlet组件中传递上下文时,使用数组传递导致子组件必须严格按顺序解构,一旦顺序变动就会出现数据不匹配甚至崩溃的问题。

现有实现代码

父组件传递上下文(数组形式):

// 父组件内
<Outlet
  context={[
    purchaseData,
    setPurchaseData,
    catsData,
    setCatsData,
    isLoading,
    setIsLoading,
    affection,
    setAffection,
    affectionColor,
    setAffectionColor,
    setHeaderBackgroundColor,
  ]}
/>

子组件尝试通过对象解构获取:

// 子组件内
const { purchaseData, setPurchaseData, catsData, setCatsData, isLoading, setIsLoading, affection, setAffection, affectionColor, setAffectionColor, setHeaderBackgroundColor, } = useOutletContext();

问题根源:父组件传递的是数组,数组按索引顺序存储,子组件用对象解构获取时,本质是把数组当成类数组对象,解构的是数组的索引键(如0、1)而非定义的变量名,因此完全按顺序匹配,和名称无关。

解决方案:传递对象而非数组

把上下文改成对象形式传递,子组件就能通过对象解构按名称获取值,不受顺序影响:

修改后的父组件代码

// 父组件内
<Outlet
  context={{
    purchaseData,
    setPurchaseData,
    catsData,
    setCatsData,
    isLoading,
    setIsLoading,
    affection,
    setAffection,
    affectionColor,
    setAffectionColor,
    setHeaderBackgroundColor,
  }}
/>

修改后的子组件代码

// 子组件内
const { purchaseData, setPurchaseData, catsData, setCatsData, isLoading, setIsLoading, affection, setAffection, affectionColor, setAffectionColor, setHeaderBackgroundColor } = useOutletContext<{
  purchaseData: 你的类型;
  setPurchaseData: 你的类型;
  catsData: 你的类型;
  setCatsData: 你的类型;
  isLoading: 你的类型;
  setIsLoading: 你的类型;
  affection: 你的类型;
  setAffection: 你的类型;
  affectionColor: 你的类型;
  setAffectionColor: 你的类型;
  setHeaderBackgroundColor: 你的类型;
}>();

说明

  • 对象是键值对结构,解构时根据键名匹配,和属性顺序完全无关,后续调整父组件对象的属性顺序,子组件解构也不会受影响。
  • 为保证TypeScript类型安全,建议给useOutletContext添加泛型定义,明确上下文的类型结构,避免类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 01:15:07