最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get state of _app.js in Next.js? - Stack Overflow

programmeradmin1浏览0评论

I have initiated a state in _app.js using Next.js. I would like to use this state in the index.js file. How can I access it?

This is my _app.js code:

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(`/`)
        .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.

I have initiated a state in _app.js using Next.js. I would like to use this state in the index.js file. How can I access it?

This is my _app.js code:

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.

Share Improve this question edited Apr 29, 2020 at 3:38 Penny Liu 17.4k5 gold badges86 silver badges108 bronze badges asked Dec 4, 2018 at 2:50 ContentopContentop 1,2413 gold badges23 silver badges45 bronze badges 3
  • You can use context. – Suman Kundu Commented Dec 4, 2018 at 4:01
  • The _app,js already uses context internally – Contentop Commented Dec 4, 2018 at 9:58
  • Just for reminder, the Container in _app has been deprecated and should be removed. App Container Deprecated – Penny Liu Commented Mar 2, 2021 at 7:53
Add a comment  | 

1 Answer 1

Reset to default 18

let's say you have this code in _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}/>

Solution 1:

Now, let's see how can we use it in index.js or any other pages

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

Solution 2:

Populate state in the index.js from props and then access it from 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

发布评论

评论列表(0)

  1. 暂无评论