【问题标题】:In ReactJS, facing problem in rendering the data from an API due to its odd structure在 ReactJS 中,由于其奇怪的结构,在从 API 呈现数据时面临问题
【发布时间】:2021-11-06 22:41:30
【问题描述】:

这是我的代码:

import React, { useState, useEffect } from "react";
import axios from 'axios';

function App() {

  const [arrName, setName] = useState();

  useEffect(() => {
    
    axios.get('URL')
        .then( response => {
          // console.log( response.data )
          setName( response.data )
        });
    
  }, [])

  const foo = () => {
    console.log(arrName.data[0].data[0]._id)
    // following two console statements need not to be in the code. I am putting them only to show the structure of API

    console.log(arrName)
    console.log(arrName.data)
  }

  return(
    <div> 
      Hi,  I'm the component 
      <button onClick={foo}> console </button>    
    </div>
  ) 
}

export default App;

控制台响应截图

我想简化以下陈述。这样我就可以轻松地迭代 API 并从 API 打印任何内容。但是,我在这里只打印一个 id。

console.log(arrName.data[0].data[0]._id)

以下命令会破坏代码

<div>  
       arrName.data[0].data.map((item) => <li>{item._id}</li> ) }
 </div>

请帮助我对我的代码进行哪些更改。

【问题讨论】:

  • 您想如何打印?我的意思是最终的预期结果?
  • 想要迭代它类似于 arrayName.map(itr =>
  • itr._id
  • )
  • 请检查我的答案,看看它是否符合您的需求。
  • 标签: reactjs axios react-hooks use-effect use-state


    【解决方案1】:

    根据回复的评论,您会这样做:

    arrName?.data &&
      arrName.data.map((item) => (
        <ul>
          {item.data.map((chidlItem) => (
            <li> {chidlItem._id} </li>
          ))}
        </ul>
      ));
    

    ?Optional Chaining,用于检查链中的引用是否有效,如果arrNamearrName.data 为空/未定义,它将跳过映射函数

    【讨论】:

    • 这段代码有效,但是当我刷新浏览器时我的代码坏了。现在得到一个错误 --> TypeError: Cannot read properties of undefined (reading 'data')
    • 哇,这行得通。谢谢你。瑞恩,你能提供一点解释吗?
    • 当然可以。给我一点时间,我会用解释更新我的答案
    【解决方案2】:

    你不能只迭代这部分吗?

    arrName.data[0].data

    for (const d of arrName.data[0].data) {
        console.log(d._id)
    }
    

    【讨论】:

    • 您应该只在评论中提出问题。您在回答中提出问题
    • 不过,他没有足够的代表发表评论
    【解决方案3】:

    我猜真正的问题是来自后端 API 发送结构化为另一个对象数组中的对象数组的数据。一种解决方案可能是将所需的值保存在您更容易访问的数组中。

    const [arrName, setName] = useState();
    
    useEffect(() => {
    
      axios.get('URL')
        .then( response => {
          // console.log( response.data )
          setName( response.data[0].data )
        });
    
    }, [])
    

    但这只是一种解决方法。

    【讨论】:

    • 我的错我应该提到代码应该更改为:
      arrName.map((item) =>
    • {item._id}
    • ) }
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签