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>
}
}