我完成了我的第一个gatsby.js项目,该项目在“ gatsby development”下运行没有错误。 但是,当我以以下方式运行build命令时: “ gatsby clean && gatsby build”,出现以下错误:
failed Building static HTML for pages - 3.164s
ERROR #95313
Building static HTML failed for path "/lectures/lecture"
See our docs page for more info on this error: https://gatsby.dev/debug-html
4 |
5 | const Links = ({ styleClass, active, children }) => {
> 6 | const { user, setUser } = useContext(UserContext);
| ^
7 |
8 | let loggedInMenus = false;
9 |
WebpackError: TypeError: Cannot destructure property 'user' of 'Object(...)(...)' as it is null.
- links.js:6 Links
src/constants/links.js:6:11
not finished Generating image thumbnails - 22.034s
现在这是我的link.js。
import React, { useContext } from 'react';
import { UserContext } from '../context/UserContext';
import { Link } from "gatsby"
const Links = ({ styleClass, active, children }) => {
const { user, setUser } = useContext(UserContext);
let loggedInMenus = false;
if (user && user.user.is_active) {
loggedInMenus = true;
}
return (
<ul className={styleClass}>
<li>
<Link to="/" className="page-link" active={active}>
Home
</Link>
</li>
<li>
{
(loggedInMenus !== true) ? (<></>) : (
<Link to="/lecture" className="page-link" active={active}>
Lectures
</Link>
)
}
</li>
</ul>
)
}
export default Links
在 src>上下文> UserContext.js 中,我具有此“用户”状态,该状态最初设置为“空”
import React, { createContext, useState } from 'react'
export const UserContext = createContext(null);
export default ({ children }) => {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
)
}
我想当它传递给Provider(?)时,它不喜欢“ user”值为null。
请问如何解决此构建错误?
答案 0 :(得分:1)
你不应该在这一行传递 null 作为上下文:export const UserContext = createContext(null);
创建一个默认上下文如下:
const defaultContext = {
user: ''
};
然后将默认的上下文变量分配给 createContext() :
export const UserContext = createContext(defaultContext);
这应该可以解决问题!