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

时间:2018-12-04 02:50:40

标签: javascript reactjs next.js

我已经使用next.js在_app.js中启动了状态。 我想在index.js文件中使用此状态。 我该如何访问?

这是我的_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>
    );

} }

很多都不相关(例如,将数据传递到Layout等)。我只想在index.js中使用此状态

谢谢

1 个答案:

答案 0 :(得分:4)

假设您在_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>
    )
  }
}

请注意state<Component {...pageProps} {...this.state}/>

解决方案1:

现在,让我们看看如何在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>
    )
  }
}

您可以像this.props.name

那样将它们用作道具

解决方案2:

index.js中的props中填充状态,然后从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.satate.name}</h2>
      </div>
    )
  }
}

您可以像this.state.name

那样将它们用作道具