3 回答

TA貢獻1852條經驗 獲得超7個贊
您的團隊數據在您的構造函數中初始化,如下所示
this.state = {
isShow: true,
team: []
};
這在第一次渲染期間導致錯誤,因為 .team.location.city 未定義。在第二次渲染中,使用新值 setState 后會很好。
要解決此問題,您需要檢查該值是否未定義或在構造函數中設置 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貢獻1848條經驗 獲得超6個贊
給定組件代碼,您state.team是一個數組,因此您需要使用數組索引來訪問它。
this.state.team[0].location.city
OFC,這假定數組已填充,因此首先使用保護檢查以確保第一個元素存在。
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;
}
}
而且由于它是一個數組,映射結果也是一種常見的模式
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);
狀態更新是“異步的”,更新發生在渲染周期之間,因此控制臺日志只會記錄此渲染周期的當前狀態。在生命周期函數中記錄更新的狀態,例如componentDidUpdate.

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