首页 > 解决方案 > NextJS - 在自定义应用程序中将状态作为道具传递给孩子

问题描述

./pages/_app.js 从官方文档中得到了这个:

import App, { Container } from 'next/app'

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps }
  }

  render () {
    const { Component, pageProps } = this.props

    return (
      <Container>
        <Component {...pageProps} />
      </Container>
    )
  }
}

export default MyApp

我想将状态从 MyApp 传递到它呈现的每个页面,但不知道如何。我试过这个:

const childProps = {
  ...
}

<Container>
  <Component {...childProps} />
</Container>

并得到一个错误:

React.Children.only expected to receive a single React element child.

标签: reactjsnext.js

解决方案


罪魁祸首是

<Link>
  <Icon />
  text
</Link>

在呈现的页面中(不是_app.js)。Link 有两个孩子(react-router Link 的残余)而不是一个。


推荐阅读