【问题标题】:Retrieve values from the array containing multiple objects from API in react?从包含来自API的多个对象的数组中检索值反应?
【发布时间】:2018-03-06 20:18:48
【问题描述】:

我正在使用 fetch 方法使用下面编写的代码从我的 react 应用程序中的 API 检索数据。

componentDidMount(){
    let auth_token = localStorage.getItem("token");
    let header_obj = {"x-access-token": auth_token};
    fetch('http://example.com/xyz', {headers: header_obj})
    .then(response => response.json())
    .then(response => {
      this.setState({
        postData:response.data  //initially set to an empty array in constructor
      })
    })
    .catch(err => {
        console.log(err);
    });
  }

这很好用。它给了我确切的响应,即包含多个对象的数组

{
  "data": [
    {
        "title": "John Doe",
        "description": "Active User",
        "dates": "4th Jan 2018"
    },
    {....} //multiple objects
  ]
 }

现在,当我尝试从响应中访问任何对象时,例如

render() {
  const {postData} = this.state;
  return (
      <div>       
         <h1>{postData[0].username}</h1> 
      </div>
    )
 }

这给了我一个错误“TypeError: Cannot read property 'username' of undefined "。我该如何解决这个问题?

【问题讨论】:

    标签: reactjs api


    【解决方案1】:

    这可能是因为在响应到达之前postData 是空数组,因此postData[0] 未定义。因此你的错误。

    对于这种特定情况,您可以尝试以下方法:

     <h1>{postData[0] && postData[0].username}</h1> 
    

    【讨论】:

    • 完美。奇迹般有效。谢谢。
    【解决方案2】:

    你必须检查 postData 尚不可用时的情况,通常你可以显示一个加载器。 if 条件取决于您如何开始您的状态,在我的回答中,我假设您已将 postData 启动为 null

    render() {
          const {postData} = this.state;
          if (!postData) {
             return (<div>Loading...</div>
          }
          return (
              <div>       
                 <h1>{postData[0].username}</h1> 
              </div>
            )
         }
    

    【讨论】:

    • @VinaySingh 因为他认为 postData 在您的构造函数中设置为 null ,但事实并非如此。
    • 太棒了。感谢您与我分享这个。
    猜你喜欢
    • 2021-11-09
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多