在React JS中使用createContext将“值”传递给提供程序

时间:2020-07-24 17:20:45

标签: javascript reactjs react-props react-functional-component

我是React JS的新手,我试图了解功能组件中的createContext()。因此,在这里我试图将存储在books中的当前状态传递给提供程序,但是我想我做错了什么。你能帮我这个吗?

上下文组件:

import React, { createContext, useState } from "react";

export const BookContext = createContext();
const BookContextProvider = (props) => {
  const [books, setBooks] = useState([
    { title: "Book 1", id: 1 },
    { title: "Book 2", id: 2 },
    { title: "Book 3", id: 3 },
    { title: "Book 4", id: 4 },
  ]);

  return (
    <BookContext.Provider value={ books }>  //<-- Doesn't work
      {props.children}
    </BookContext.Provider>
  );
};

export default BookContextProvider;

我要使用上下文的组件:

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

const BookList = () => {

  const { books } = useContext(BookContext);

  return (
    <div>
      <ul>
        {books.map((book) => (
          <li key={book.id}>
            {book.title}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default BookList;

1 个答案:

答案 0 :(得分:0)

您没有将默认值传递给createContext()