-1

沙盒中的代码:https://codesandbox.io/s/goofy-dhawan-n2kk2?file=/src/components/NavBar.jsx

错误:TypeError: Cannot destructure property 'books' of 'Object(...)(...)' as it is undefined.

4

1 回答 1

1

默认情况下,您正在导出一个组件,它是上下文提供者。如果您想在其他地方使用上下文,那么您应该在导入时解构它,因为它不是默认导出。

import React, { useContext } from "react";
import { BookContext } from "../contexts/BookContexts";

const NavBar = () => {
  // Error is here
  const { Books } = useContext(BookContext);
  // Error is here
  return (
    <div className="navbar">
        <h1>Reading list</h1>
        <p>We currently have {Books.length} to read</p>
    </div>
  );
};
export default NavBar;

App.js

import React from "react";
import "./styles.css";
import NavBar from './components/NavBar';
import BookContextProvider from "./contexts/BookContexts";

export default function App() {
  return (
    <div className="App">
      <BookContextProvider>
      <NavBar />
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      </BookContextProvider>
    </div>
  );
}

BookContexts.js

import React, { useState, createContext } from "react";
import uuid from "uuid/v1";
export const BookContext = createContext({
  Books: [],
  addBook: () => {},
  delBook: () => {}
});

const BookContextProvider = props => {
  const [Books, setBooks] = useState([
    { title: "title 1", author: "Author 1", id: 1 },
    { title: "title 12", author: "Author 2", id: 2 }
  ]);
  // eslint-disable-next-line
  const addBook = (title, author) => {
    setBooks([...Books, { title: title, author: author, id: uuid() }]);
  };
  // eslint-disable-next-line
  const delBook = id => setBooks(Books.filter(book => book.id !== id));
  return (
    <BookContext.Provider value={{ Books, addBook, delBook }}>
      {props.children}
    </BookContext.Provider>
  );
};
export default BookContextProvider;

这是固定的沙盒链接

于 2020-04-26T09:09:35.353 回答