我正在尝试显示APi响应的一部分,但是当我尝试解析它时,它一直给我未定义的含义。
我尝试执行API响应的2部分,但均无济于事。
class App extends Component {
constructor() {
super();
this.state = {
head: 0,
data: [],
firstName: "Brad",
lastName: "Marchand",
err: null
};
}
componentDidMount() {
axios
.get("http://localhost:3001/api/player", {
params: {
firstName: this.state.firstName,
lastName: this.state.lastName
}
})
.then(response => {
this.setState({
data: response.data
});
console.log(this.state.data);
})
.catch(err => {
//this.err = err;
});
}
render() {
return (
<>
<p>{this.state.data.players[0].player.firstName}</p>
<p>Hello</p>
</>
);
}
}
后端
request(options, (err, response, body) => {
if (err) {
signale.error(err);
}
var data = JSON.parse(body);
//var data = JSON.stringify(data.players);
//var data = JSON.parse(data);
signale.success(data);
res.send(data);
});
{ lastUpdatedOn: '2019-08-15T15:20:13.791Z',
[0] players: [ { player: [Object], teamAsOfDate: [Object] } ],
[0] references: { teamReferences: [ [Object] ], venueReferences: [ [Object] ] } }
另一个预期的响应 Another response
尝试仅从响应中输出我想要的内容,但始终无法通过this.state.data进行定义
答案 0 :(得分:0)
所以这里的问题是,您正在componentDidMount中进行API调用,并且API的响应肯定会在初始渲染之后出现,并且在初始渲染中,this.state.data.players[0].player.firstName
是未定义的,并且会破坏您的代码。在访问该值之前,请添加条件检查。同样将data
状态初始化为一个对象
class App extends Component {
constructor() {
super();
this.state = {
head: 0,
data: {},
firstName: "Brad",
lastName: "Marchand",
err: null
};
}
componentDidMount() {
axios
.get("http://localhost:3001/api/player", {
params: {
firstName: this.state.firstName,
lastName: this.state.lastName
}
})
.then(response => {
this.setState({
data: response.data
});
console.log(this.state.data);
})
.catch(err => {
//this.err = err;
});
}
render() {
return (
<>
<p>{this.state.data.players && this.state.data.players[0].player.firstName}</p>
<p>Hello</p>
</>
);
}
}
答案 1 :(得分:0)
React setState()是异步工作的,这意味着在状态中设置值会稍有延迟。您可以将回调传递给setState(),一旦状态更新,就会调用该回调。
this.setState({
data: response.data
}, () => { console.log(this.state.data); });
干杯