Как импортировать компонент в компонент в nextjs

#reactjs #next.js

Вопрос:

Я создал компонент hello, я извлек данные API в проверенном браузере компонента hello http://localhost:3000/hello работает нормально, я хочу импортировать внутри index.js компонент теперь я проверяю http://localhost:3000/. но данные не поступают, какие проблемы. не могли бы вы, пожалуйста, решить эту проблему, пожалуйста, ниже моего кода

hello.js:

 function Hello({ posts }) {
  console.log(posts)
    return (
      <>
      <ul>
         {posts.map((post) =>(
            <p>{post.name}</p>
          ))}
      </ul>
      </>
    )
  }
  
  // This function gets called at build time on server-side.
  // It won't be called on client-side, so you can even do
  // direct database queries. See the "Technical details" section.
  export async function getServerSideProps() {
    // Call an external API endpoint to get posts.
    // You can use any data fetching library
    const res = await fetch('https://jsonplaceholder.typicode.com/users')
    const posts = await res.json()
  
    // By returning { props: { posts } }, the Blog component
    // will receive `posts` as a prop at build time
    return {
      props: {
        posts,
      },
    }
  }
  
  export default Hello
 

index.js

 import React from 'react';
// import Layout from "../components/layout";
// import NavBar from "../components/navbar";
import Hello from './hello'
function Index() {
  return (
    <>
        <Hello />
    </>
  )
}
export default Index;
 

Ответ №1:

Я почти уверен, что вы можете использовать getServerSideProps только в компоненте страницы, а не во встроенном компоненте. Поэтому решение этой проблемы состоит в том, чтобы импортировать его в index.js а затем отправьте данные на hello.js через реквизит.

ИЗМЕНИТЬ: вот код —>

hello.js

 function Hello(props) {
    return (
      <>
      <ul>
         {props.posts.map((post) =>(
            <p>{post.name}</p>
          ))}
      </ul>
      </>
    )
  }
  
  export default Hello
 

index.js

  import React from 'react';
 import Hello from './hello'
 function Index({posts}) {
   return (
     <>
         <Hello posts={posts}/>
     </>
   )
 }

export async function getServerSideProps() {
        const res = await fetch('https://jsonplaceholder.typicode.com/users')
        const posts = await res.json()

        return {
          props: {
            posts
          },
        }
      }

export default Index;
 

Комментарии:

1. Какие реквизиты я хочу отправить, не могли бы вы, пожалуйста, решить эту проблему.

2. Действительно спасибо тебе потрясающе

3. если это сработало, я буду признателен, если вам понравится мой ответ, он мне нужен, чтобы снова разблокировать вопрос о публикации.