【问题标题】:Cannot read property 'protocol' of undefined React Js无法读取未定义的 React Js 的属性“协议”
【发布时间】:2019-07-16 10:02:49
【问题描述】:

如何显示来自 JSON 文件的 author.name 数据,因为我在尝试运行时遇到错误我是 react js 的新手,所以请指导我如何解决此错误,我还添加了错误页面图像,以便您查看

class Details extends Component {
    constructor(props){
        super(props);

        this.state = {
            question: [],
          };
    }

  componentDidMount() {
    axios.get(`http://trivago-magazine-work-sample-server.s3-website.eu-central-1.amazonaws.com/dornoch-castle-scotland-whisky.json`)
      .then(res => {
        const question = res.data;
        console.log(res);
        this.setState({ question });
      })

  }


    render() {
        const {question} = this.state;

        if (question === null) return <p>Loading ...</p>;
        return (
            <div>

            <Container>
                <Row >

                    <h4>{question.author.name}</h4> //This Line when i try to show author.name it showing error 

                </Row>
            </Container>



            </div>
        )
    }
}

export default Details

Here is the image of error page

【问题讨论】:

    标签: javascript json reactjs api


    【解决方案1】:

    初始状态应为{ question: null },以便if (question === null)生效并呈现“Loading...”消息。

    【讨论】:

      【解决方案2】:

      第一次改变:

      this.state = {
               question: null,
                };
      

      如果有问题,你必须提出一个条件:

      {question && 
         <h4>{ question.author.name}</h4> 
      }
      

      【讨论】:

        猜你喜欢
        • 2014-02-16
        • 1970-01-01
        • 2021-12-06
        • 2021-07-12
        • 2018-05-24
        • 2016-08-06
        • 1970-01-01
        • 2022-11-17
        • 2020-12-24
        相关资源
        最近更新 更多