无法使用“ useContext”钩子破坏上下文提供者中传递的值

时间:2020-04-26 08:54:26

标签: reactjs react-hooks use-context

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

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

1 个答案:

答案 0 :(得分: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;

这是固定的沙箱link