我已经创建了hello组件,我在hello组件检查浏览器http://localhost:3000/hello中获取API数据工作正常,我想在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;
我很确定你只能在页面组件中使用getServerSideProps,而不能在嵌入式组件中使用。因此,解决这个问题的方法是在index.js中导入它,然后通过props.
将数据发送到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;