【问题标题】:Destructuring this.props into Component将 this.props 解构为 Component
【发布时间】:2020-07-03 10:22:38
【问题描述】:

在下面的示例代码中:它是React 和Next.js

import App, { Container} from "next/app";
import React from "react";

class MyApp extends App{
    render() {
        const { Component } = this.props;
        return (
            <Container>
                <p>Hey I am on every page</p>
                <Component/>
            </Container>
        )
    }
}

export default MyApp;

我的问题是关于这一行的:

const { Component } = this.props;

我的问题: 这是如何工作的?这是我拥有的最高页面级别。那么是谁将this.props 传递给它呢? 那是什么语法?为什么叫Components?他能不能叫别的?

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    您的 MyApp 组件扩展了一个名为 App 的组件,它是一个内部 Next react 组件。您想要扩展App 的原因是,如果您在在每个页面加载之前调用getInitialProps。您可以将 App 视为一个 HOC(高阶组件),它在 MyApp first 中调用 getInitialProps,然后是页面中的其他 Next 方法,例如:getInitialProps、getServerSideProps、@ 987654330@, getStaticPaths 秒。

    这创建了一个渲染阻塞场景,MyApp.getInitialProps 可以阻止页面级方法的执行,直到它被解决。

    在您的情况下,您甚至不需要扩展 App,因为您没有调用 getInitialProps,相反,您可以只使用纯函数(或者如果您不需要包含元数据,则完全删除 _app.js或者用某种布局组件包装每个page):

    function MyApp({ Component, pageProps }) {
      return (
        <Component {...pageProps} />
      );
    }
    
    export default MyApp;
    

    所有后续的pages(如/pages/example.js)将作为名为@9​​87654339@ 的道具传递给这个MyApp 组件,而从上述方法之一返回的任何道具都将作为名为@9​​87654340 的道具传递给MyApp @道具。

    你可以有点这样想App(下一个/应用程序):

    import React, { Component } from "react";
    import MyApp from "../_app.js"; // custom _app page
    import Example from "../example.js"; // a page component
    
    class App extends Component {
      static async getInitialProps(ctx) {
        const { pageProps } = await MyApp.getInitialProps(ctx);
        return { pageProps }; // this.props.pageProps
      };
    
      render() {
        return <MyApp Component={Example} pageProps={this.props.pageProps} />
      }
    }
    

    --

    附带说明,Container 组件自 v9.0.4 以来一直是 deprecated

    【讨论】:

      【解决方案2】:

      Component 属性是活动页面,因此每当您在路线之间导航时,Component 将更改为新页面。因此,您发送给Component 的任何props 都会被页面接收。

      【讨论】:

        猜你喜欢
        • 2016-11-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-31
        • 1970-01-01
        相关资源
        最近更新 更多