【发布时间】:2020-12-08 17:28:41
【问题描述】:
当我尝试在 booklis.jsx 中解构 Bookcontext 时,它不起作用并显示:
TypeError: 无法解构 'Object(...)(...)' 的属性 'books' 因为它是未定义的。
bookcontext.jsx
// 功能组件
import { createContext, useState } from "react";
export const Bookcontext = createContext();
const BookcontextProvider = (props) => {
const [books, setBook] = useState([
{ title: ' Name of the wind ', id: 1 },
{ title: ' Name of the Blind ', id: 2 },
{ title: ' Name of the Love', id: 3 },
{ title: ' Name of the Shine ', id: 4 },
])
return (
<div>
<BookcontextProvider value={{ books }}>
{props.childrean}
</BookcontextProvider>
</div>
);
};
export default BookcontextProvider;
booklis.jsx
import React, { useContext } from "react"; 从“../Context/Themcontext”导入{ Themcontext }; 从“../Context/Bookcontext”导入{ Bookcontext };
/// 如何在函数组件中使用上下文 野兔是demu
const Booklis = () => {
const { isLightThem, light, dark } = useContext(Themcontext);
const { books, setbook } = useContext(Bookcontext);
const theme = isLightThem ? light : dark;
return (
<div>
<div
className="book-list"
style={{ color: theme.sintex, background: theme.bg }}
>
<ul>
{books.map((boe) => {
return (
<li key={boe.id} style={{ background: theme.ui }}>
{boe.title}{" "}
</li>
);
})}
</ul>
</div>
</div>
);
};
export default Booklis;
【问题讨论】:
-
Booklis是否呈现在BookcontextProvider的 React 树中?此外,您不会将setbook传递给上下文的值,也不会提供有效的初始上下文值。 -
那里没有错字吗:
{props.childrean}不应该是{props.children}?
标签: reactjs