Javascript 如何将在app.js中获取的数据传递给组件
在我的nextjs项目中,我有一个需要api调用的布局组件。我不想在每个页面(./pages/*)中调用api调用,而是将逻辑放在一些全局空间中。我做了一些研究,看起来覆盖app.js是nextjs文档()中指出的方法 我已经列出了如下代码。但它似乎不起作用 ./pages/_app.jsJavascript 如何将在app.js中获取的数据传递给组件,javascript,reactjs,next.js,Javascript,Reactjs,Next.js,在我的nextjs项目中,我有一个需要api调用的布局组件。我不想在每个页面(./pages/*)中调用api调用,而是将逻辑放在一些全局空间中。我做了一些研究,看起来覆盖app.js是nextjs文档()中指出的方法 我已经列出了如下代码。但它似乎不起作用 ./pages/_app.js function MyApp({ Component, appProps, results }) { return ( <Layout {...results}> <
function MyApp({ Component, appProps, results }) {
return (
<Layout {...results}>
<Component {...appProps} />
</Layout>
)
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext)
const results = await getResults() //api call
return { appProps, results }
}
函数MyApp({Component,appProps,results}){
返回(
)
}
MyApp.getInitialProps=async(appContext)=>{
const appProps=await App.getInitialProps(appContext)
const results=wait getResults()//api调用
返回{appProps,results}
}
./components/Layout.js
const Layout = ({ children, results }) => {
return (
<React.Fragment>
<Header/>
<div className='row col-md-8 offset-md-2'>
{JSON.stringify(results)} //results is nothing here
<div className='col-md-9'>
{children}
</div>
</div>
</React.Fragment>
)
}
const布局=({children,results})=>{
返回(
{JSON.stringify(results)}//results在这里什么都不是
{儿童}
)
}
./pages/index.js
...
return (
<>
{head()}
<Layout>
<div className='row col-md-12'>
{showContents()}
</div>
</Layout>
</>
)
。。。
返回(
{head()}
{showContents()}
)
我肯定我错过了一些显而易见的事情。任何帮助都将不胜感激 除非您希望该页面每次都返回类似的结果,否则您应该在客户端迁移api调用。Next.JS已经从getInitialProps转移到getStaticProps(获取静态数据)、GetStaticPath(预呈现一组静态页面)和getServerSideProps(这可能与getInitialProps最接近,在服务器端获取数据)。有关next.js数据获取的更多信息,请访问: 现在根据您提供的代码回答您的问题
// index.js
<Layout> <- you're not passing any props here.
//index.js
除非您希望该页面每次都返回类似的结果,否则您应该在客户端迁移api调用。Next.JS已经从getInitialProps转移到getStaticProps(获取静态数据)、GetStaticPath(预呈现一组静态页面)和getServerSideProps(这可能与getInitialProps最接近,在服务器端获取数据)。有关next.js数据获取的更多信息,请访问:
现在根据您提供的代码回答您的问题
// index.js
<Layout> <- you're not passing any props here.
//index.js
嗨,这都是你的密码吗?您是否有类似于“render()”的函数在异步完成后运行?您好,这是您的全部代码吗?您是否有类似于在异步完成后运行的“render()”函数?
import { useState } from 'react'
function useCats(){
const [cats, setCats] = useState()
useEffect(() => {
fetch('https://test.api/cats')
.then(response => response.json())
.then(_cats => setCats(_cats));
}, [])
return cats
}
// then in another component
function CatsList(){
const cats = useCats();
if(!cats){
return <p>Loading</p>
}
return <div>
{cats.map(cat => <p key={cat.id}>Cat: {cat.name}</p>)}
</div>
}