javascript - 如何在 Next.js 中获取 _app.js 的状态?
问题描述
我已经启动了_app.js
使用 Next.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>
);
}
}
其中很多是无关紧要的(比如将数据传递给布局等......)。我想做的就是在我的index.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>
)
}
}
请注意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
在from中填充状态,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.state.name}</h2>
</div>
)
}
}
你可以像这样使用它们作为道具this.state.name
推荐阅读
- xamarin.forms - GPS开启后需要使用xamarin表单获取当前位置
- php - 使用 PHP 的 JSON 到 HTML 行
- perl - 另一种设置 DB::deep 的方法?
- android - 懒惰的 Android 依赖项。如何在 gradle 依赖解析之前构建 AARs 库
- sql - 查看 sys.database_principals 中所有用户的最低权限
- javascript - CastError:在路径的起息日转换为日期失败
- bootstrap-4 - 如何在中心获取表格
- java - 问题:Jsoup 用 < 后跟 word 解析字符串
- mysql - 用于数据库迁移的 Nifi
- webpack - Webpack 已使用与 API 模式不匹配的配置对象进行初始化。- 配置 [0] 具有未知属性“模式”