我已创建REST API端点,即localhost:5000/api/match/:match_id
现在我想从此端点获取数据并在前端显示它,但我收到了未定义的错误。
在server.js中:
//Get a particular match stats
app.get('/api/match/:match_id', (req, res) =>{
let match = req.params.match_id;
matches.findOne({id: parseInt(match)}).then(Match =>{
res.json(Match);
});
});
在matchinfo.js中:
import React, { Component } from 'react';
class Matchinfo extends Component {
constructor(props){
super(props);
this.state = {
info:[],
loading:true
};
}
componentDidMount(){
fetch('api/match/:match_id')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
info:res,
loading:false
})
})
}
render() {
if (this.state.loading) {
return <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" />
}
return (
<div>
<p class="match">MATCH {info.id}</p>
<h4>{info.team1}</h4>
<p>VS</p>
<h4>{info.team2}</h4>
<div class="winner">
<h3>WINNER</h3>
<h4>{info.winner}</h4>
</div>
</div>
);
}
}
export default Matchinfo;
在matchinfo组件中,我在编译完成后无法编译,请参阅屏幕截图以获得更多说明。
JSON响应:
答案 0 :(得分:1)
尝试以下更新的代码。它应该按预期工作
import React, { Component } from 'react';
class Matchinfo extends Component {
constructor(props){
super(props);
this.state = {
info:[],
loading:true
};
}
componentDidMount(){
fetch('api/match/:match_id')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
info:res,
loading:false
})
})
}
renderLoading(){
<img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" />
}
render() {
const {info} = this.state;
return (
<div>
{this.state.loading ? this.renderLoading(): ''}
{this.state.info.length > 0 && (
<div>
<p class="match">MATCH {info.id}</p>
<h4>{info.team1}</h4>
<p>VS</p>
<h4>{info.team2}</h4>
<div class="winner">
<h3>WINNER</h3>
<h4>{info.winner}</h4>
</div>
</div>
)}
</div>
);
}
}
export default Matchinfo;