useContext返回一个空数组

时间:2020-10-05 21:58:54

标签: reactjs

我正在创建一个功能组件,并试图将其状态作为上下文传递。 useEffect挂钩用数据填充状态,我创建了一个自定义挂钩以将结果返回给我。当我尝试在另一个组件中使用它时,我总是得到一个空数组。请帮忙

上下文组件:

import React, {useState, useEffect, useContext, createContext} from 'react'
import DB from './Database'

export const Database = createContext()

export const useFeaturedHotels = () => {
  return useContext(Database)
}

export const DatabaseProvider = ({children}) => {
  const [state, setState] = useState({
    featuredHotels: [],
  })

  useEffect(() => {
    const featuredHotels = DB.hotels.filter((hotel) => hotel.featured === true)
    setState(featuredHotels)
  }, [])

  return <Database.Provider value={state}>{children}</Database.Provider>
}

孩子:

import React from 'react'
import {useFeaturedHotels} from './DatabaseContext'
import Card from '@material-ui/core/Card'
import CardContent from '@material-ui/core/CardContent'
import Button from '@material-ui/core/Button'
import {makeStyles} from '@material-ui/core'

const HomeHotels = () => {
  const classes = useStyles()
  const featuredHotels = useFeaturedHotels() // ----> always empty array
  console.log(featuredHotels)
}

1 个答案:

答案 0 :(得分:0)

我确实建议像这样使用

@click
import React, {useState, useEffect, useContext, createContext} from 'react'
import DB from './Database'

export const Database = createContext()

export const DatabaseProvider = ({children}) => {
  const [state, setState] = useState({
    featuredHotels: [],
  })

  useEffect(() => {
    const featuredHotels = DB.hotels.filter((hotel) => hotel.featured === true)
    setState(featuredHotels)
  }, [])

  return <Database.Provider value={state}>{children}</Database.Provider>
}

这应该有效。 我从未使用过您的模式。我现在看看它为什么不起作用