无法读取未定义的属性(读取‘0’)
2021-11-07
58101
我有一个用 React 和 NextJS 钩子编码的页面,当我尝试呈现页面时,错误显示标题中的内容,我推测这是因为我映射的对象在第一次加载时为空/未定义。我在页面上的每个映射中添加了“?”,但仍然出现此错误...我注意到,如果在出现错误后我停留在该页面上并按“Ctrl + shift + r”,页面会正常加载。这可能是什么原因造成的?
import {Fragment, useEffect} from "react";
import Head from "next/head";
import DashboardPage from "../../../../components/components/dashboard/DashboardPage";
import LayoutDashboard from "../../../../components/layout/LayoutDashboard";
import React from "react";
import Pusher from "pusher-js";
import useSWR, {mutate} from "swr";
const fetcher = async () => {
const response1 = await fetch("API");
const data1 = await response1.json();
const props = {
data: data1,
};
return props;
};
export default function Dashboard(props) {
const {data, error} = useSWR("data", fetcher);
useEffect(() => {
//Pusher.logToConsole = true;
var pusher = new Pusher("pshr", {
cluster: "eu",
});
const channel = pusher.subscribe("chnl");
channel.bind("chnl", function (data) {
console.log(data);
mutate("data");
});
}, []);
if (error) return "Error";
if (!data) return "Loading";
console.log(data);
return (
<Fragment>
<Head>
<title>Dashboard</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<LayoutDashboard restaurantData={props?.restaurantData[0]}>
<DashboardPage
orders={data?.showItemsOnOrder}
dashboardCards={data?.dashboardCardInfo}
ordersGraph={data?.dashboardGraph}
/>
</LayoutDashboard>
</Fragment>
);
}
export async function getStaticPaths() {
const response = await fetch(`API`);
const data = await response.json();
const tables = [];
for (var i = 1; i <= data[0].restaurantTables; i++) {
tables.push({
restaurant: data[0].queryName,
tableNr: i.toString(),
});
}
return {
paths: tables.map((table) => {
return {
params: {
restaurantName: table.restaurant,
tableNr: table.tableNr,
},
};
}),
fallback: false,
};
}
export async function getStaticProps() {
const response = await fetch(`API`);
const data = await response.json();
return {
props: {
restaurantData: data,
},
revalidate: 1,
};
}
编辑 我意识到,如果我直接转到我想要的链接,网站会正常运行...当我在 nextJS 中调用带有 Link 标签的组件时,它会停止工作,然后它会抛出一个错误,提示它在标题中...因此,如果我直接转到链接,一切都会按预期运行,也许这也是我单击链接然后刷新它时页面可以正常运行的原因...那么 Link 标签可能存在什么问题?这是我的代码:
<Link
href={{
pathname: "/restaurant/restaurantName/dashboard/",
query: {restaurantName: restaurantName},
}}
>
<div
className={
router.pathname == "/restaurant/[restaurantName]/dashboard"
? "text-blue-600 bg-gray-50"
: "text-gray-700 "
}
>
<div className="flex p-3 space-x-4 0 hover:bg-gray-50 hover:text-blue-600 cursor-pointer">
<DonutLargeIcon className=" text-gray-300" />
<p className="">Dashbord</p>
</div>
</div>
</Link>
3个回答
1-如果在第一次组件渲染时数据未定义,我认为这种方法可行
- 第一次数据未定义
- 获取秒时间数据,然后您可以使用以下方法
const fetcher = async () => {
const response1 = await fetch("API");
const data1 = await response1.json();
const props = {
data: data1,
};
return props;
};
-
如果查看您的获取函数,则
return props= {data: data1
-
const {data} =useSWR("data",fetching)
它应该是 data.data.showItemOnOrder
return (
<Fragment>
<Head>
<title>Dashboard</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<LayoutDashboard restaurantData={props?.restaurantData[0]}>
{data&& <DashboardPage
orders={data.data.showItemsOnOrder}
dashboardCards={data.data.dashboardCardInfo}
ordersGraph={data.data.dashboardGraph}
/>}
</LayoutDashboard>
</Fragment>
);
BlueDragon
2021-11-07
对于尝试从对象内部的数组获取数据并收到此错误的人 - 您可以尝试使用
length
进行检查,如下所示:
object?.array.length ? object?.array?.someItem![0] : 'not exist'
请注意,我们使用链接符号(
[?]
)和逻辑非(
!
)进行检查,以实现更安全的搜索。
Erik P_yan
2022-03-30
您的 useEffect 需要依赖数组中的
data
,以便根据
data
触发重新渲染。此外,您需要在此 useEffect 顶部使用
if (!data) return
来防止出现错误。
因此:
useEffect(() => {
//Pusher.logToConsole = true;
if (!data) return
var pusher = new Pusher("pshr", {
cluster: "eu",
});
const channel = pusher.subscribe("chnl");
channel.bind("chnl", function (data) {
console.log(data);
mutate("data");
});
}, [data]);
Mark Williams
2021-11-07