简体   繁体   English

如何在 Next.js 中获取 _app.js 的状态?

[英]How to get state of _app.js in Next.js?

I have initiated a state in _app.js using Next.js.我已经使用 Next.js 在_app.js启动了一个状态。 I would like to use this state in the index.js file.我想在index.js文件中使用这个状态。 How can I access it?我怎样才能访问它?

This is my _app.js code:这是我的_app.js代码:

import React from 'react';
import App, { Container } from 'next/app';
import Layout from '../components/Layout';

export default class MyApp extends App {
  constructor(props) {
    super(props);
    this.state = {
      currencyType: {
        name: 'Ether',
        price: 1,
      },
      ethPriceUsd: 1,
    };
  }

  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};
    let ethPriceUsd;

    if (Component.getInitialProps) {
      fetch(`https://api.coingecko.com/api/v3/coins/ethereum/`)
        .then((result) => result.json())
        .then((data) => {
          ethPriceUsd = parseFloat(data.market_data.current_price.usd).toFixed(
            2
          );
        });
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps, ethPriceUsd };
  }

  componentDidMount() {
    const ethPriceUsd = this.props.ethPriceUsd;
    this.setState({ ethPriceUsd });
  }

  onCurrencyTypeChange(currencyTypeValue) {
    let currencyType = {};
    //Value comes from Header.js where Ether is 0 and USD is 1
    if (currencyTypeValue) {
      currencyType = {
        name: 'USD',
        price: this.state.ethPriceUsd,
      };
    } else {
      currencyType = {
        name: 'Ether',
        price: 1,
      };
    }
    alert('We pass argument from Child to Parent: ' + currencyType.price);
    this.setState({ currencyType });
  }

  render() {
    const { Component, pageProps } = this.props;
    return (
      <Container>
        <Layout changeCurrencyType={this.onCurrencyTypeChange.bind(this)}>
          <Component {...pageProps} />
        </Layout>
      </Container>
    );
  }
}

A lot of it is irrelevant (Like passing the data to the Layout etc...).很多都是无关紧要的(比如将数据传递给布局等......)。 All I want to do is use this state in my index.js .我想要做的就是在我的index.js使用这个状态。

let's say you have this code in _app.js .假设您在_app.js有此代码。

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

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

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

    return { pageProps }
  }

  state = {
    name: "Morgan",
  }

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

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

Please notice the state and <Component {...pageProps} {...this.state}/>请注意state<Component {...pageProps} {...this.state}/>

Solution 1:解决方案1:

Now, let's see how can we use it in index.js or any other pages现在,让我们看看如何在index.js任何其他页面中使用它

import React from 'react';

export default class Index extends React.Component {

  render() {
    return (
      <div>
        <h2>My name is {this.props.name}</h2>
      </div>
    )
  }
}

You can use them as props like this this.props.name您可以将它们用作像this.props.name这样的道具

Solution 2:解决方案2:

Populate state in the index.js from props and then access it from stateprops填充index.js state,然后从state访问它

import React from 'react';

export default class Index extends React.Component {

   constructor(props) {
       super(props)
       this.state ={
           name: this.props.name
       }
   }

  render() {
    return (
      <div>
        <h2>My name is {this.state.name}</h2>
      </div>
    )
  }
}

You can use them as props like this this.state.name您可以将它们用作像this.state.name这样的道具

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Next.js - _app.js state 在页面刷新/SSR 时丢失 - Next.js - _app.js state is lost on page refresh / SSR 等待_app.js加载,然后在Next.js上运行组件 - Wait _app.js loaded then run component on Next.js Next.js 和 Typescript - 如何在功能组件中访问 app.js 的 props 和 staticProps - Next.js with Typescript - how to access app.js props and staticProps in functional component 如何在 _app.js 中使用 getStaticProps 在 Next.js 的每个页面中显示从 api 获取的数据 - How to use getStaticProps in _app.js for showing data fetched from api in every pages in Next.js 如何将 next.js 中的 pageProps 从子组件传递给 _app.js? - How to pass pageProps in next.js from a child component to _app.js? 如何修复 Next.js 中 _app.js 中包含的 Sonarqube“重命名此文件”代码异味? - How to fix Sonarqube "Rename this file" code smell that contained in _app.js in Next.js? 如何在 App.js next.js 中的服务器端加载数据 - How to Server Side load data in App.js next.js 为什么将 app.js 更改为 app.tsx 会破坏我的 Next.js 项目? - Why does changing app.js to app.tsx break my Next.js project? 为什么我无法访问 Next.js 应用程序“_app.js”中的 window? - Why can't I access the window in Next.js app '_app.js'? Next.js - 页面未将 GetServerSideProps 放入页面组件道具中(使用自定义 _app.js) - Next.js - Page not getting GetServerSideProps into Page component props (with custom _app.js)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM