[英]Next.js App crashed if prop is undefined when destructuring code?
I will try to explain my problem, I have created a custom Context API wrapper for all my data.我将尝试解释我的问题,我为我的所有数据创建了一个自定义 Context API 包装器。 Now, I have this
docType
which is not always defined nor existing.现在,我有这个
docType
,它并不总是定义也不存在。
When I destructure it like so:当我这样解构它时:
const { docType } children?.props?.data; // My Next App / JS crashes and getting the undefined error.
Doing this works:这样做有效:
const docType = children.props.data?.docType;
I am not really sure why this happens.我不太确定为什么会这样。 destructuring all other data props will fail if I don't write my code like so:
如果我不这样写我的代码,解构所有其他数据道具将失败:
import { createContext, useContext } from "react";
const AppContext = createContext();
export const AppWrapper = ({ children }) => {
const docType = children.props.data?.docType;
const site = children.props.data?.site;
const page = children.props.data?.page;
const preview = children.props?.preview;
const sharedState = {
docType,
preview,
page,
site,
};
return (
<AppContext.Provider value={sharedState}>{children}</AppContext.Provider>
);
};
export const useAppContext = () => useContext(AppContext);
Can someone explain to me why I am getting this problem?有人可以向我解释为什么我会遇到这个问题吗?
You can use like this:你可以这样使用:
const { docType, site, page, site} = children?.props?.data || {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.