next.js 将数据数组转换为服务器端的React组件,但我希望React组件在客户端呈现

idv4meu8  于 9个月前  发布在  React
关注(0)|答案(1)|浏览(122)

假设我正在使用react-bootstrap中的Carcass和Carcass.Item。这只能在客户端呈现。
我想将服务器上的数据转换为HTML,但我仍然不想在服务器端呈现组件。
我为什么要这样做呢?为了提高网站的SEO。

const data = [1,2,3,4];

// I want this to be rendered on the server and return 
const items = data.map(i => <Carousel.Item>i</Carousel.Item>);

// I want this to return to the client and the client should be responsible of rendering the Carousel.
/*
// <Carousel>
//     <Carousel.Item>1</Carousel.Item>
//     <Carousel.Item>2</Carousel.Item>
//     <Carousel.Item>3</Carousel.Item>
//     <Carousel.Item>4</Carousel.Item>
// </Carousel>
*/
return <Carousel>{items}</Carousel>

字符串

wnavrhmk

wnavrhmk1#

但我仍然不想在服务器端呈现组件。
客户端组件首先在服务器上呈现。如果您的组件具有客户端API函数(useState,useEffect,onClick),由于这些函数在服务器上不可用,因此您的组件将抛出错误。通过使用use client,它只是说忽略这些API,将其发送到客户端,客户端将负责。这就是hydration
水合是将事件侦听器附加到DOM的过程,以使静态HTML具有交互性。在幕后,水合是使用hydrateRoot React API完成的。

后续导航

在随后的导航中,客户端组件完全呈现在客户端上,而没有服务器呈现的HTML。

相关问题