为了账号安全,请及时绑定邮箱和手机立即绑定

似乎无法在 React 中从此 api 检索数据

似乎无法在 React 中从此 api 检索数据

白衣染霜花 2023-06-29 20:54:31
import react from 'react';    export default class App extends react.Component {  state = {    loading: true,    person: null,  }难以获取要呈现的数据。数据确实显示在控制台日志上,但不会在反应页面上显示名称,请帮助。任何帮助将不胜感激,谢谢
查看完整描述

2 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

这是 API 响应:


[{"id":1,"title":"Mr","firstName":"Danny","lastName":"Dyer","dob":"24/07/1977","active":true},{"id":2,"title":"Mr","firstName":"Nicholas","lastName":"Cage","dob":"07/01/1964","active":true},{"id":3,"title":"Miss","firstName":"Emma","lastName":"Watson","dob":"15/04/1990","active":true},{"id":4,"title":"Prof","firstName":"Bryan","lastName":"Cox","dob":"03/03/1968","active":true}]

它是一个对象数组。仅当 API 响应是包含属性的对象data.res[0]时才有意义,例如res


{

  "res": [

    {"id":1, ...

因此,将您的代码更改为


person: data.res[0]


person: data[0]

和来自


<div>{this.state.person.name.title}</div>

<div>{this.state.person.name.first}</div>

<div>{this.state.person.name.last}</div>


<div>{this.state.person.title}</div>

<div>{this.state.person.firstName}</div>

<div>{this.state.person.lastName}</div>

正确导航数据。


(还要确保将url字符串分隔符'或", not括起来< >)


直播片段:


class App extends React.Component {

  state = {

    loading: true,

    person: null,

  }

  componentDidMount() {

    const url = 'https://api.jsonbin.io/b/5e9ef690435f5604bb4567dd';

    fetch(url)

      .then(response => response.json())

      .then(data => this.setState({ person: data[0], loading: false }));

  }


  render() {

    return (

      <div>

        {this.state.loading || !this.state.person ? (

          <div>loading...</div>

        ) : (

            <div>

              <div>{this.state.person.title}</div>

              <div>{this.state.person.firstName}</div>

              <div>{this.state.person.lastName}</div>

            </div>

          )}

      </div>

    );

  }

}

ReactDOM.render(<App />, document.querySelector('.react'));

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>

<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div class="react"></div>


查看完整回答
反对 回复 2023-06-29
?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

实际上我用不同的方式做到了!{this.state.loading || !this.state.person ? (



查看完整回答
反对 回复 2023-06-29
  • 2 回答
  • 0 关注
  • 141 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信