next提供了在服务端运行的getInitialProps方法,我们可以在这个方法中执行接口获取页面数据。
function hrefObj(url) {
if (!url.includes('?')) {
return {}
}
var localarr = url.split("?")[1].split("&");
var tempObj = {};
for (var i = 0; i < localarr.length; i++) {
tempObj[localarr[i].split("=")[0]] = localarr[i].split("=")[1];
}
return tempObj
}
-----------
import React, { useEffect, useState } from 'react'
import hrefObj from '../../static/js/urlObj'
function Downland(props) {
useEffect(() => {
console.log(props)console.log(props)
})
return (
<div><div>
)
}
Downland.getInitialProps = async (res) => {
const id = res.req ? hrefObj(res.req.url).id : res.query.id
return { id }
};
getInitialProps传入的参数中有一个req对象即url域名后面的参数,可以通过hrefObj解析得到,值得一提的是在刷新getInitialProps方法在跳转页面的过程中有可能获取不到req对象这时候就通过res.query来获取路径上的参数,
在最后要return出页面需要的参数,在react页面对象上可以通过props获取,并渲染到dom上最后发送给浏览器前端,前端请求到的dom是携带有接口数据的因此能被搜索引擎的爬虫抓取到。
有些全局使用的数据肯定不能在每个页面都去执行因此在_app.js中的 getInitialProps来执行这些操作。
在_app.js中的getInitialProps和子页面中的getInitialProps不同,他可以接受一个对象,对象中有Component, ctx两个参数。其中Component就是子页面,ctx为传入Component.getInitialProps方法中的参数。
在_app.js中我们要去执行子页面中的getInitialProps拿到数据并在render中传给子页面。
import App, {Container} from 'next/app'
import React from 'react'
import '../static/css/common.scss'
import { init } from '../plugins/getData'
export default class MyApp extends App {
static async getInitialProps({Component, ctx}) {
let pageProps = {}
if (Component.getInitialProps) {// 执行当前页面的getInitialProps
let data = await Component.getInitialProps(ctx)
pageProps = {...data}
}
return {pageProps}
}
async componentDidMount() {
if (this.props.router.pathname != '/_error') {
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?292c3026c555200d85ceefd89797a4c4";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
}
}
render () {
const {Component, pageProps} = this.props
return <Container>
<Component {...pageProps} />
</Container>
}
}