未处理的拒绝(TypeError):无法读取未定义的属性“城市”

我目前正在开发一个网站,在这里可以检索团队信息:


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})

            console.log('inside teaminfo... ' + this.state.team.location.city);

        })

    }

 render() {

        return(

         <div><h1>{this.state.team.location.city}</h1></div>

)}

}

这是团队 JSON 答案的结构:


{

    "name": "Barcelona",

    "shield": "shield.png",

    "location": {

        "city": "Barcelona",

        "country": "SPAIN"

    },

    "score": 74626,

}

我正在尝试访问团队位置 this.state.team.location.city ,因为当我在控制台中登录时它显示正确,但Unhandled Rejection (TypeError): Cannot read property 'city' of undefined显示在网站中。


任何提示或帮助将不胜感激。


慕神8447489
浏览 207回答 3
3回答

慕姐4208626

您的团队数据在您的构造函数中初始化,如下所示this.state = {&nbsp; isShow: true,&nbsp; team: []};这在第一次渲染期间导致错误,因为 .team.location.city 未定义。在第二次渲染中,使用新值 setState 后会很好。要解决此问题,您需要检查该值是否未定义或在构造函数中设置 location.city 的初始值。render() {&nbsp; &nbsp; &nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<div><h1>{typeof this.state.team.location !== "undefined"&nbsp; && typeof this.state.team.location.city !== "undefined" && this.state.team.location.city}</h1></div>)}

慕勒3428872

给定组件代码,您state.team是一个数组,因此您需要使用数组索引来访问它。this.state.team[0].location.cityOFC,这假定数组已填充,因此首先使用保护检查以确保第一个元素存在。this.state.team[0] && this.state.team[0].location.city您也可以有条件地渲染它export default class TeamInfo extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; isShow: true,&nbsp; &nbsp; &nbsp; team: []&nbsp; &nbsp; };&nbsp; &nbsp; this.getTeam();&nbsp; }&nbsp; getTeam() {&nbsp; &nbsp; const axios = require("axios");&nbsp; &nbsp; const team_id = this.props.id;&nbsp; &nbsp; axios.get(API + "/team/" + team_id).then(res => {&nbsp; &nbsp; &nbsp; this.setState({ team: res.data });&nbsp; &nbsp; });&nbsp; }&nbsp; render() {&nbsp; &nbsp; return this.state.team[0] ? (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <h1>{this.state.team[0].location.city}</h1>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; ) : null;&nbsp; }}而且由于它是一个数组,映射结果也是一种常见的模式export default class TeamInfo extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; isShow: true,&nbsp; &nbsp; &nbsp; team: []&nbsp; &nbsp; };&nbsp; &nbsp; this.getTeam();&nbsp; }&nbsp; getTeam() {&nbsp; &nbsp; const axios = require("axios");&nbsp; &nbsp; const team_id = this.props.id;&nbsp; &nbsp; axios.get(API + "/team/" + team_id).then(res => {&nbsp; &nbsp; &nbsp; this.setState({ team: res.data });&nbsp; &nbsp; });&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; {this.state.team.map(team => (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h1>{team.location.city}</h1>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; );&nbsp; }}笔记:this.setState({team : res.data})console.log('inside teaminfo... ' + this.state.team.location.city);状态更新是“异步的”,更新发生在渲染周期之间,因此控制台日志只会记录此渲染周期的当前状态。在生命周期函数中记录更新的状态,例如componentDidUpdate.

墨色风雨

您也可以使用新的 ES2020 链运算符来检查对象中是否存在属性,如下所示:&nbsp; render() {&nbsp; &nbsp; return (&nbsp; {this.state.team.map(team => (&nbsp; &nbsp; {team?.location ?<div><h1>{team.location.city}</h1></div>: null}&nbsp; ))}&nbsp; );&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript