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

React Router useOutletContext类型错误:invoiceList不存在于Invoice[]类型

问题:解构useOutletContext时提示invoiceList不存在于Invoice[]类型上

我在Root组件中设置了类型,然后在useOutletContext钩子中解构prop,为什么invoiceList不存在于Invoice[]类型上?我是不是误解了什么?

Root组件代码

import { ReactElement, useEffect, useState } from "react";
import { Outlet } from "react-router-dom";
import { Bar } from "../../components/Bar/Bar";
import { Invoice } from "../InvoiceList/InvoiceList.utils";

type Props = {};

const Root = (props: Props): ReactElement => {
  const [invoiceList, setInvoiceList] = useState<Invoice[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch("./data.json");
      const data = await response.json();

      setInvoiceList(data);
    };

    fetchData();
  }, []);

  return (
    <div>
      <Bar />
      <Outlet context={{ invoiceList }} />
    </div>
  );
};

InvoiceList组件代码

import { ReactElement } from "react";
import { useOutletContext } from "react-router";
import styled from "styled-components";
import { Invoice } from "./InvoiceList.utils";
import { InvoiceListHeader } from "./InvoiceListHeader/InvoiceListHeader";
import InvoiceListItem from "./InvoiceListItem/InvoiceListItem";

type Props = {};

const InvoiceList = (props: Props): ReactElement => {
  const { invoiceList } = useOutletContext<Invoice[]>(); //Property 'invoiceList' does not exist on type 'Invoice[]'.

  return (
    <div>
      <InvoiceListHeader />
      <List>
        {invoiceList.map((item) => {
          return (
            <InvoiceListItem
              key={item.id}
              item={item}
              invoiceList={invoiceList}
            />
          );
        })}
      </List>
    </div>
  );
};

错误提示截图

错误提示


原因与解决方案

核心问题

你在Root组件中传给Outlet的context是一个包含invoiceList属性的对象,但在InvoiceList组件中错误地将useOutletContext的类型声明为Invoice[](数组类型),两者类型不匹配导致TS报错——数组上不存在invoiceList这个属性。

具体说明

  • Root组件里的<Outlet context={{ invoiceList }} />实际传递的是结构为{ invoiceList: Invoice[] }的对象
  • 但你在InvoiceList中用useOutletContext<Invoice[]>()告诉TS:这个context是一个Invoice数组,所以解构invoiceList属性时,TS会判定数组没有该属性,抛出错误。

解决方案

方案1:定义共享的Context类型(推荐)

先在Root组件或共享类型文件中定义context的类型:

// 比如在Root组件顶部添加
type RootOutletContext = {
  invoiceList: Invoice[];
};

然后在Root组件中传递context时(可选,增强类型严谨性):

<Outlet context={{ invoiceList } as RootOutletContext} />

最后在InvoiceList组件中使用正确的类型获取context:

const { invoiceList } = useOutletContext<RootOutletContext>();

方案2:直接在useOutletContext中声明对象类型

如果不想单独定义类型,可以直接在useOutletContext中指定对象结构:

const { invoiceList } = useOutletContext<{ invoiceList: Invoice[] }>();

两种方案都能让TS正确识别context的结构,解决报错问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:40:23