无法读取未定义的React Js的属性“协议”

时间:2019-07-16 10:02:49

标签: javascript json reactjs api

如何显示JSON文件中的author.name数据,因为在尝试运行时遇到错误,因此我是React JS中的新手,因此指导我如何解决此错误,我还添加了错误页面图像,以便您可以看到< / p>

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

第一次更改:

this.state = {
         question: null,
          };

如果有问题,您必须提出条件:

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