简体   繁体   中英

Which brackest should be used where ? square brackets or curly braces while object destructuring ? I'm tyring to use context but bit confused

This is my context and I want to use it in my BookList component.

import React, { createContext, useState } from "react"
import { v4 as uuidv4 } from "uuid"

export const BookContext = createContext()

const BookContextProvider = (props) => {
  const [books, setBooks] = useState([
    { title: "Deek Work", author: "Cal Newport", id: 0 },
    { title: "Principles", author: "Ray Dalio", id: 1 },
    { title: "Sapiens", author: "Yuval Noah Harari", id: 2 },
    { title: "Grit", author: "Angela Duckworth", id: 3 },
    { title: "Ikagai", author: "Hector Garcia", id: 4 },
  ])

  const addBook = (title, author) =>
    setBooks([...books, { title, author, id: uuidv4() }])

  const removeBook = (id) => setBooks(books.filter((book) => book.id !== id))

  return (
    <BookContext.Provider value={{ books, addBook, removeBook }}>
      {props.children}
    </BookContext.Provider>
  )
}

export default BookContextProvider

The BookList component:

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

const BookList = () => {
  const { books } = useContext(BookContext)
}

Why the books variable is inside the curly braces and not square braces? even though the state ie books is created with useState hook is an array.

Why the books variable is inside the curly braces and not square braces?

Because useContext(BookContext) returns the { books, addBook, removeBook } object that you passed as the value to the provider. To destructure that object, you use curly brackets.

Sure, books itself is an array, but that doesn't matter - you're not destructuring it to get the array elements. To do that, you'd do something like

const [firstBook, secondBook, ...otherBooks] = books;

or even in one go:

const { books: [firstBook, secondBook, ...otherBooks] } = useContext(BookContext);
  • [] is used for destructuring arrays
  • {} is used for destructuring objects

According to https://reactjs.org/docs/hooks-reference.html

useContext(BookContext)

"Accepts a context object (the value returned from React.createContext) and returns the current context value for that context."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM