Reactjs 财产';文本';:在Next.js中未定义
我试图从API中获取数据,但在尝试在功能组件中显示数据时出错 标题代码:Reactjs 财产';文本';:在Next.js中未定义,reactjs,api,next.js,Reactjs,Api,Next.js,我试图从API中获取数据,但在尝试在功能组件中显示数据时出错 标题代码: Header.getInitialProps = async ({ req, query }) => { const protocol = req ? `${req.headers['x-forwarded-proto']}:` : location.protocol const host = req ? req.headers['x-forwarded-host'] : location.h
Header.getInitialProps = async ({ req, query }) => {
const protocol = req
? `${req.headers['x-forwarded-proto']}:`
: location.protocol
const host = req ? req.headers['x-forwarded-host'] : location.host
const pageRequest = `${protocol}//${host}/api/announcements/announcement?id=1`
const res = await fetch(pageRequest)
const json = await res.json()
return json
}
function Header({ ad }) {
return (
<Row>
<Sheet>
<SheetHeader>Ogłoszenia</SheetHeader>
<Row alignCenter={true} width="200%" paddingTop="30px">
{ad.text}
</Row>
</Sheet>
</Row>
)
}
已部署,显示500个内部服务器错误,如下所示:我从getInitialProps切换到async componentDidMount(),现在可以工作了
class Header extends Component {
constructor(props) {
super(props)
this.state = { json: {} }
}
async componentDidMount () {
const pageRequest = `https://core.mdcholewka.now.sh/api/announcements`
const res = await fetch(pageRequest)
const json = await res.json()
this.setState({ data: json })
}
render() {
return (
<Row>
<Sheet>
<SheetHeader>Ogłoszenia</SheetHeader>
<Row alignCenter={true} width="200%" paddingTop="30px">
{this.state.data.map(ad => {
{ad.text}
})}
</Row>
</Sheet>
</Row>
)
}
}
类头扩展组件{
建造师(道具){
超级(道具)
this.state={json:{}
}
异步组件didmount(){
常量页面请求=`https://core.mdcholewka.now.sh/api/announcements`
const res=等待获取(pageRequest)
const json=await res.json()
this.setState({data:json})
}
render(){
报税表(
奥格奥斯泽尼亚
{this.state.data.map(ad=>{
{ad.text}
})}
)
}
}
API返回{ads}
(ads
是我能告诉数组的范围),并且您的组件尝试访问ad.text
。同样的错误。在返回API之前,当您登录json
时,您会得到什么?我从getInitialProps切换到async componentDidMount(),现在可以工作了!