我的nextjs项目中有一个ThemeProvider问题。
我最讨厌将数据传递给主题的最佳方法是什么。
在/pages/index
内部的getInitialProps中,获取设置数据,ThemeProvider标签位于/pages/_app.js
包装器<Component />
中。如何将数据从索引传递到_app?任何想法?
谢谢!
这是我的代码:
/pages/_app.js
import App from "next/app";
import React from "react";
import Head from "next/head";
/* Styles */
import { ThemeProvider } from "styled-components";
import theme from "../styles/theme/primary";
class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<>
<ThemeProvider theme={theme}> // Here ThemeProvider whit theme
<Header />
<Container>
<Component {...pageProps} />
</Container>
<Footer />
</ThemeProvider>
</>
);
}
}
export default MyApp;
pages / index.js
import React, { useState, useEffect } from "react";
/* Others */
import { getData } from "../helper/api";
const Index = props => {
const res = props.data;
return (
<>
<Home data={res} />
</>
);
};
Index.getInitialProps = async ({ res }) => {
try {
let req = await getData(); // Here I get the settings.
return { data: req };
} catch (e) {
console.log(`Error: ${e}`);
return { data: null};
}
};
export default Index;