用next框架開發(fā)了一段時(shí)間,講一下next怎么發(fā)起請(qǐng)求獲取從服務(wù)器獲取數(shù)據(jù)
一。頁面首次打開請(qǐng)求數(shù)據(jù)
自己封裝的next請(qǐng)求封裝庫 有興趣的小伙伴可以看一下
import React from 'react';
import { getTopicsApi } from '../../util/service'; // 自己封裝的請(qǐng)求
class Demo extends React.Components {
// 第二種寫法
static getInitialProps() {
// ...
}
render() {
const { topicsList } = this.props // 通過props獲取
return (
<div>demo{topicsList}</div>
)
}
}
// 第一種寫法
Demo.getInitialProps = async function() {
const options = {
page: 1,
size: 10
}
const res = await getTopicsApi(options);
return {
topicsList: res
};
};
export default Demo
這種方法獲取數(shù)據(jù)是在服務(wù)端完成,通過打開network查看元素發(fā)現(xiàn),整個(gè)頁面時(shí)包括數(shù)據(jù)生成的頁面結(jié)構(gòu)都是一次性返回的。這樣的好處是有利于seo優(yōu)化,百度爬蟲能抓取到頁面的內(nèi)容。 這是估計(jì)有小伙伴會(huì)問了,我要通過點(diǎn)擊一些按鈕又要發(fā)送請(qǐng)求要怎么發(fā)?
二。頁面動(dòng)態(tài)請(qǐng)求數(shù)據(jù)
import React from 'react';
import { getTopicsApi } from '../../util/service'; // 自己封裝的請(qǐng)求
class Demo extends React.Components {
state = {
list: []
}
// 第二種寫法
static getInitialProps() {
// ...
}
componentDidMount() {
this.setState(old => ({
list: this.props.topicsList
}))
}
async getList() {
const options = {
page: 2,
size: 10
}
const res = await getTopicsApi(options);
this.setState(old => ({
list: res
}))
}
render() {
const { topicsList } = this.props // 通過props獲取
return (
<div>
demo{topicsList}
<button onClick={this.getList.bind(this)}>點(diǎn)我啊</button>
</div>
)
}
}
// 第一種寫法
Demo.getInitialProps = async function() {
const options = {
page: 1,
size: 10
}
const res = await getTopicsApi(options);
return {
topicsList: res
};
};
export default Demo
這種方法獲取數(shù)據(jù)是在瀏覽器完成的,跟用spa單頁面應(yīng)用請(qǐng)求數(shù)據(jù)的形式是一樣,熟悉的感覺又回來了~