在组件的单​​独文件中使用React钩子

时间:2020-10-07 03:49:50

标签: javascript reactjs react-hooks

我想为我的项目创建一个数据文件,而不是将所有内容都放在一个文件中,但是我正在使用React钩子加载图像。当我想将所有内容放在单独的文件中时,这将成为一个问题。该代码为我提供了“无效的钩子调用”消息,我知道它为什么出错,但无法弄清楚如何使其对我有用。

EventData.js

import React from "react"
import Image from "gatsby-image"
import { graphql, useStaticQuery } from "gatsby"

const getImages = graphql`
  {
    btu: file(relativePath: { eq: "eventImage/btu.jpeg" }) {
      childImageSharp {
        fixed(height: 120, width: 500) {
          ...GatsbyImageSharpFixed_withWebp_tracedSVG
        }
      }
    }
  }
`

const data = useStaticQuery(getImages)
export const details = [
  {
    id: 1,
    img: <Image fixed={data.btu.childImageSharp.fixed} />,
    date: "2 Oct 2020",
    distance: "30km - 160km",
    name: "Brisbane Trail Ultra",
    location: "Brisbane, QLD",
  },
]

EventCalendar.js

const EventCalendar = () => {
  return (
    <Layout>
      <section>
        {details.map(details => {
          return <EventCard key={details.id} {...details}></EventCard>
        })}
      </section>
    </Layout>
  )
}

2 个答案:

答案 0 :(得分:1)

您必须定义一个自定义钩子,在您的情况下看起来像这样:

import React from "react"
import Image from "gatsby-image"
import { graphql, useStaticQuery } from "gatsby"

const getImages = graphql`
  {
    btu: file(relativePath: { eq: "eventImage/btu.jpeg" }) {
      childImageSharp {
        fixed(height: 120, width: 500) {
          ...GatsbyImageSharpFixed_withWebp_tracedSVG
        }
      }
    }
  }
  `;

export function useDetails() {    
  const data = useStaticQuery(getImages);

  return [
    {
      id: 1,
      img: <Image fixed={data.btu.childImageSharp.fixed} />,
      date: "2 Oct 2020",
      distance: "30km - 160km",
      name: "Brisbane Trail Ultra",
      location: "Brisbane, QLD",
    },
  ];
}

要定义自定义钩子,请定义一个函数,该函数返回所需的值。在此功能中,您可以从react API中获得所有可用的钩子。

然后在您的主文件中写入

const EventCalendar = () => {
  const details = useDetails();

  return (
    <Layout>
      <section>
        {details.map(detail => {
          return <EventCard key={details.id} {...detail}></EventCard>
        })}
      </section>
    </Layout>
  )
}

答案 1 :(得分:0)

仅来自React函数的调用挂钩 不要通过常规JavaScript函数调用Hook。相反,您可以:

✅从React函数组件中调用Hook。

✅从自定义挂钩中调用挂钩(我们将在下一页中了解它们)。 另一件事: 在地图内,您应该将细节更改为细节,因为它是项

const EventCalendar = () => {
  return (
    <Layout>
      <section>
        {details.map(detail => {
          return <EventCard key={details.id} {...detail}></EventCard>
        })}
      </section>
    </Layout>
  )
}

您可以在此处了解有关钩子的信息:https://reactjs.org/docs/hooks-rules.html

我的建议是您可以将其包装到这样的组件中:

const ImageHook = () => {
  const data = useStaticQuery(getImages)
  return <Image fixed={data.btu.childImageSharp.fixed}/>
}

export const details = [
  {
    id: 1,
    img:  <ImageHook />,
    date: "2 Oct 2020",
    distance: "30km - 160km",
    name: "Brisbane Trail Ultra",
    location: "Brisbane, QLD",
  },
]