reactjs nextjs app router prop id not match react chrono

r7s23pms  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(103)

我用app router创建了nextjs应用程序。我在app文件夹中有一个页面,比如app/about/page. jsx。我想在那个页面上使用react chrono库的时间轴。
所以我在src/components/时间轴创建了时间轴组件。

'use client'

import React from 'react'
import {Chrono} from 'react-chrono'

const Timeline = () => {
  const items = [
    {
      title: 'January 2022',
      cardTitle: 'Event 1',
      cardSubtitle: 'Event 1 Subtitle',
      cardDetailedText: 'This is the first event on the timeline.'
    },
    {
      title: 'February 2022',
      cardTitle: 'Event 2',
      cardSubtitle: 'Event 2 Subtitle',
      cardDetailedText: 'This is the second event on the timeline.'
    },
    {
      title: 'March 2022',
      cardTitle: 'Event 3',
      cardSubtitle: 'Event 3 Subtitle',
      cardDetailedText: 'This is the third event on the timeline.'
    }
  ]
  return (
    <Chrono
      mode="HORIZONTAL"
      items={items}
      showAllCardsHorizontal
      cardWidth={450}
      cardHeight={300}
      contentDetailsHeight={100}
      fontSizes={{
        title: '1rem'
      }}
      slideShow
      key={1}
    />
  )
}

字符串
而当我用在关于页面的那个组件上时;

import Timeline from '@/components/Timeline'

export default function About() {
  return <Timeline />
}


我得到的错误像;

Warning: Prop `id` did not match. Server: "react-chrono-timeline-UECK0Np" Client: "react-chrono-timeline-BXPbvjM"


但如果我导入时间轴与下一个/动态与ssr假它的工作,我不会得到错误。

const Timeline = dynamic(() => import('@/components/Timeline'), {ssr: false})


我认为“使用客户端”和动态ssr错误是一样的。我在哪里犯了错误,或者这是正确的用法?

jjhzyzn0

jjhzyzn01#

警告“Prop id did not match. Server:... Client:...”是Next.js应用程序中的常见问题,特别是在使用react-chrono等生成动态ID的库时。这是由于服务器端渲染的标记和客户端渲染的标记之间不匹配。
要解决这个问题,您可以将Chrono组件的渲染延迟到组件挂载之后,确保它只在客户端渲染。下面是使用useEffect钩子控制渲染的组件的修订版本:

const [isClient, setIsClient] = useState(false);

      useEffect(() => {
        setIsClient(true); // Component has mounted, update state to trigger re-render   
}, []);

字符串
然后当返回时:

{isClient && (
        <Chrono 
          items={items}
          mode="HORIZONTAL"
          theme={theme}
          // Other Chrono props as needed
        />
      )}

相关问题