从React调用API [英] Call API from React

查看:756
本文介绍了从React调用API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让React从Django Rest Framework API中获取JSON.链接的编写方式如下: http://127.0.0.1:8000/band /api/1/?format = json ,其结构如下:

I am trying to get React to get the JSON from the Django Rest Framework API. The link is written like so http://127.0.0.1:8000/band/api/1/?format=json and the structure is as below:

{
id: 1,
name: "Muse",
date_added: "2017-04-17",
image: "https://upload.wikimedia.org/wikipedia/commons/a/a3/Muse_melbourne28012010.jpg",
bio: "Muse are an English rock band from Teignmouth, Devon, formed in 1994. The band consists of Matt Bellamy (lead vocals, guitar, piano, keyboards), Chris Wolstenholme (bass guitar, backing vocals, keyboards) and Dominic Howard (drums, percussion)."
}

我的反应是这样写的:

class ItemLister extends React.Component {
    constructor() {
    super();
         this.state={items:[]};
  }
  componentDidMount(){
    fetch(`http://127.0.0.1:8000/band/api/1/?format=json`)
        .then(result=>result.json())
        .then(items=>this.setState({items}))
        setTimeout(() => console.log(this.state.items), 2000)
  }
  render() {
    return(
        <ul>
          {this.state.items.length ?
            this.state.items.map(item=><li key={item.id}>{item.name}</li>)
            : <li>Loading...</li>
          }
      </ul>
   )
  }
}

ReactDOM.render(
  <ItemLister />,
  document.getElementById('container')
);

HTML容器div保持正在加载... ,控制台未显示任何错误.我知道它与JSON有关,但无法弄清楚它是什么,感谢任何帮助!

The HTML container div stays at loading..., the console shows no errors. I know its something to do with the JSON but cannot figure out what it is, any help appreciated!

按照m_callens的建议添加以下内容后:

After adding the below as suggest by m_callens:

setTimeout(()=> console.log(this.state.items),2000)

setTimeout(() => console.log(this.state.items), 2000)

控制台返回我确实试图获取的对象,但是它仍然无法在页面上呈现.

the console returns the object that i am indeed trying to get but it still does not render on the page.

Object {id: 1, name: "Muse", date_added: "2017-04-17", image: "https://upload.wikimedia.org/wikipedia/commons/a/a3/Muse_melbourne28012010.jpg", bio: "Muse are an English rock band from Teignmouth, Dev…eyboards) and Dominic Howard (drums, percussion)."}

推荐答案

因此,在经过长时间的日志记录和调试之后,我认为我已经弄清了这个问题.

So after the long process of logging and debugging, I think I've figured out the issue.

您的初始状态是将items属性创建为array,因此您尝试将每个项目映射到<li>以呈现到UI,但是您从fetch调用并将this.state.items重新分配给array不是一个简单的对象.因此,当您尝试map对象时,它会失败,并解释为什么length条件始终会失败.

Your initial state is creating the items property as an array and thus you're trying to map each item to an <li> to render to your UI, however the value you're getting back from your fetch call and reassigning this.state.items to isn't an array but a simple object. Therefore when you try to map the object, it fails, also explaining why your length condition is always failing.

与其在第二次对获取的.then处理中直接重新分配items,请用此版本的setState替换它以维护array结构.

Instead of directly reassigning items in the second .then handling of your fetch, replace it with this version of setState to maintain the array structure.

...
  .then(newItem => this.setState((prevState, props) => ({
        items: [...prevState.items, newItem]
      })
    )
  )

您可能还希望在组件的生命周期中将fetch调用从componentDidMount挂钩推回到componentWillMount挂钩.

You may also want to push the fetch call back in the lifecycle of the component from the componentDidMount hook to the componentWillMount hook.

这篇关于从React调用API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆