【问题标题】:Next.js react-spring useTransition - Invariant Violation: invalid hook callNext.js react-spring useTransition - 不变违规:无效的钩子调用
【发布时间】:2022-06-10 23:01:16
【问题描述】:

我正在尝试将 useTransition 添加到我的 Next.js 项目中,但它给了我这个错误:

Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component.

目前我什至不担心代码是否有效,我只是不明白为什么useTransition 挂钩被认为是无效的。我在跑步:

"next": "12.1.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-spring": "9.4.5-beta.1",

代码如下:

const ProductImages = (() => {
  return ({ images }) => {
    const [currentImage, setCurrentImage] = useState(3)

    const transitions = useTransition(images[currentImage], currentImage, {
      from: { opacity: 0, transform: 'scale(1.1)' },
      enter: { opacity: 1, transform: 'scale(1)' },
      leave: { opacity: 0, transform: 'scale(0.9)' },
    })

    return (
      <Wrapper>
        {transitions.map(({ item, props, key }) => {
          return (
            <animated.MainImage key={key} style={{ ...props }}>
              <img src={`../${item}`} />
            </animated.MainImage>
          )
        })}
        <SubImageRow>
          {images.map((image, i) => {
            return (
              <SubImage active={currentImage === i} key={i} onClick={() => setCurrentImage(i)}>
                <img src={`../${image}`} alt={'image'} />
              </SubImage>
            )
          })}
        </SubImageRow>
      </Wrapper>
    )
  }
})()

请帮帮我,谢谢!

【问题讨论】:

  • 由于某种原因,您的整个组件都包含在 return ({ images }) =&gt; { 中。你需要把 useState 和 useTransition 等拉出来,因为现在函数组件体中基本上什么都没有。

标签: javascript next.js react-spring usetransition


猜你喜欢
  • 2020-12-01
  • 2020-02-16
  • 1970-01-01
  • 2019-10-20
  • 2018-12-16
  • 2018-06-13
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
相关资源
最近更新 更多