API显示在控制台中,但不显示在浏览器窗口中

时间:2019-01-29 03:50:17

标签: reactjs api

class App extends Component {

  state = {
    persons: ''
  }

  componentDidMount() {

    axios.get(`https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=pokemon&utf8=&format=json`)
      .then(res => {
        const persons = res;
        this.setState({
          persons
        });
        console.log(this.state.persons.data.query.search[0].title);
      })
  }
  render() {

    return (
      <div className="App">
        <p>this.state.persons.data.query.search[0].title</p>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

这是因为您的state.persons在初始化时为空,请尝试首先进行验证:

render() {
   return (
      <div className="App">
        <p>{this.state.persons ? this.state.persons.data.query.search[0].title : null}</p>
      </div>
   );
}
相关问题