3 回答

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
您的團(tuán)隊(duì)數(shù)據(jù)在您的構(gòu)造函數(shù)中初始化,如下所示
this.state = {
isShow: true,
team: []
};
這在第一次渲染期間導(dǎo)致錯(cuò)誤,因?yàn)?.team.location.city 未定義。在第二次渲染中,使用新值 setState 后會(huì)很好。
要解決此問(wèn)題,您需要檢查該值是否未定義或在構(gòu)造函數(shù)中設(shè)置 location.city 的初始值。
render() {
return(
<div><h1>{typeof this.state.team.location !== "undefined" && typeof this.state.team.location.city !== "undefined" && this.state.team.location.city}</h1></div>
)}

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
給定組件代碼,您state.team是一個(gè)數(shù)組,因此您需要使用數(shù)組索引來(lái)訪問(wèn)它。
this.state.team[0].location.city
OFC,這假定數(shù)組已填充,因此首先使用保護(hù)檢查以確保第一個(gè)元素存在。
this.state.team[0] && this.state.team[0].location.city
您也可以有條件地渲染它
export default class TeamInfo extends React.Component {
constructor(props) {
super(props);
this.state = {
isShow: true,
team: []
};
this.getTeam();
}
getTeam() {
const axios = require("axios");
const team_id = this.props.id;
axios.get(API + "/team/" + team_id).then(res => {
this.setState({ team: res.data });
});
}
render() {
return this.state.team[0] ? (
<div>
<h1>{this.state.team[0].location.city}</h1>
</div>
) : null;
}
}
而且由于它是一個(gè)數(shù)組,映射結(jié)果也是一種常見(jiàn)的模式
export default class TeamInfo extends React.Component {
constructor(props) {
super(props);
this.state = {
isShow: true,
team: []
};
this.getTeam();
}
getTeam() {
const axios = require("axios");
const team_id = this.props.id;
axios.get(API + "/team/" + team_id).then(res => {
this.setState({ team: res.data });
});
}
render() {
return (
{this.state.team.map(team => (
<div>
<h1>{team.location.city}</h1>
</div>
))}
);
}
}
筆記:
this.setState({team : res.data})
console.log('inside teaminfo... ' + this.state.team.location.city);
狀態(tài)更新是“異步的”,更新發(fā)生在渲染周期之間,因此控制臺(tái)日志只會(huì)記錄此渲染周期的當(dāng)前狀態(tài)。在生命周期函數(shù)中記錄更新的狀態(tài),例如componentDidUpdate.

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
您也可以使用新的 ES2020 鏈運(yùn)算符來(lái)檢查對(duì)象中是否存在屬性,如下所示:
render() {
return (
{this.state.team.map(team => (
{team?.location ?<div><h1>{team.location.city}</h1></div>: null}
))}
);
}
添加回答
舉報(bào)