我对React&NextJS很陌生,来自PHP语言。这对我来说很有趣,也很激动-但是还没有掌握到这一部分。
您可以在 getInitialProps 中检查是否为空吗?例如,如果API关闭或API未返回任何结果,则显示错误消息?
请原谅我发布代码,但这是...
import App, { Container } from 'next/app';
import Layout from '../components/Layout';
import Footer from '../components/Footer';
import 'isomorphic-fetch'; // Library for fetching data
import Link from 'next/link';
import {Jumbotron, Button, Row} from 'reactstrap';
export default class Index extends React.Component {
static async getInitialProps() {
// Connect to the API
const ApiResponse = await fetch('http://localhost:1337/mods')
// Store the data fetched from ApiResponse
const ModsData = await ApiResponse.json()
// return mods (first is table name in API, second is the ModsData variable above where we store the json data)
return {
mods: ModsData
}
}
render() {
return <Layout>
<span style={{borderBottom: '1px solid #ccc', paddingBottom: '5pt', marginTop: '5pt'}}>
<h4 style={{paddingTop: '10pt'}}>Showing all mods</h4>
</span>
<ul className="list-group" style={{paddingTop: '10pt'}}>
{this.props.mods.map(Mod => // Get our mods & loop over them
<li className="list-group-item" key={Mod.id}>
<Link as={`/mods/${Mod.id}`} prefetch href={`/mods/id=${Mod.id}`}><a>
{Mod.name}</a></Link>
{Mod.description}
</li>
)}
</ul>
</Layout>
}
}
答案 0 :(得分:1)
只需添加另一个道具noData
,然后检查ModsData
是否返回任何内容,否则返回noData: true
否则noData: false
static async getInitialProps() {
let noData = false
// Connect to the API
const ApiResponse = await fetch('http://localhost:1337/mods').then((value) => {
if(!value) noData = true;
}).catch(err => {
noData = true;
})
// Store the data fetched from ApiResponse
const ModsData = await ApiResponse.json()
// return mods (first is table name in API, second is the ModsData variable above where we store the json data)
return {
mods: ModsData,
noData
}
}
render(){
if(this.props.noData) return <h1>No Data</h1>
//return other code
}
答案 1 :(得分:1)
试一试完美吗?如果出错,您可以将error
设置为道具的一部分