【问题标题】:Reactjs fetch method returns empty arrayReactjs fetch 方法返回空数组
【发布时间】:2019-07-22 11:50:44
【问题描述】:

我正在尝试获取一些数据,格式为:

[
  {
    "id": 1,
    "some_data": "..."
  },
  ...
]

我想要得到的是一个列表,显示来自获取的项目。如果我将相同的数据放在项目中的一个文件中,它就可以工作。

但是,当我尝试映射它时,我收到一条错误消息“this.data.map 不是函数”。所以我通过使用Array.from() 对其进行了一些更改。目前看起来是这样的:

export default class Main extends React.Component { 
  constructor(props) {
    super(props);
    this.state = {
      items = [];
    };
    this.getData = this.getData.bind(this);
  }

  getData = () => {
    fetch("URL",{
      method: "get",
      header: { "Content-Type": "application/json" }
    })
    .then(response => {
      var array = Array.from(response.json())
      this.setState({items: array});
    })
  }

  render() {
    const list = this.state.items.map((r, i) => {
      return (
        <Item
          id = { r[i].id }
          some_data = { r[i].some_data }
          ...
        />
      )
    })
    return(
      <div>
        <Item
          p = {list}
        >
      </div>
    )
  }
}

【问题讨论】:

  • 您的数据可能不在服务响应的“根”。尝试 console.log(response) 查看响应内容并查找包含您的数据的节点。可能是您的数据在 response.data 中,请尝试使用 console.log。通常,来自服务的响应对象包含的不仅仅是数据......
  • @ChrisAdams 如果我在控制台记录我得到的响应:>Promise {: Array(15)} 展开后,我看到了我想要显示的数据。
  • 得到什么?什么都没有?
  • 你在哪里调用方法getData()你通常在componentDidMount调用它
  • 我添加了一个方法componentDidMount,我称之为getData()

标签: json reactjs fetch


【解决方案1】:

首先不需要状态来存储响应。由于状态值而发生的事情没有反映在您的渲染中。

  1. 在成功响应中调用函数并在函数中映射响应并在此处设置状态。

  1. 将下面的代码放在渲染函数之外,分配给如下变量

    常量列表 = this.state.items.map((r, i) => { 返回 ( ) }) 返回( ) }

    渲染(){ {列表} }

【讨论】:

    【解决方案2】:

    试试这样的.....

    最好在安装组件后加载数据。另外,没有 URL,我假设你已经隐藏了这个。

    一旦您“看到”响应内容,您就可以相应地对其进行编码。

    export default class Main extends React.Component { 
        constructor(props) {
            super(props);
            this.state = {
              items = [];
            };
            // this.getData = this.getData.bind(this);
        }
    
        componentDidMount(){
    
            // Attempt to load data once component mounted.
    
            this.getData();
    
        }
    
        getData = () => {
            // Don't you need the URL below, or have you deliberately hidden it?
            fetch("URL",{
            method: "get",
            header: { "Content-Type": "application/json" }
        })
        .then(response => {
    
            console.log(response);  // See exactly what is in response....
    
            var array = Array.from(response.json())
            console.log(array);  // Check array is really what you want
    
            // You could try a JSON.Parse....
            var jsonArray = JSON.Parse(response);
            console.log(jsonArray);
    
            this.setState({items: array});
         })
      }
    
      render() {
          const list = this.state.items.map((r, i) => {
          return (
              <Item
              id = { r[i].id }
              some_data = { r[i].some_data }
               ...
            />
           )
        })
        return(
          <div>
           <Item
              p = {list}
            >
         </div>
        )
       }
    }
    

    【讨论】:

    • console.log(response) 返回对象的一些信息。如果我放一个console.log(this.state.items),那么它会返回一个空数组。
    • 你的意思是响应包含你想要的数据?你能分享一下回复吗?此外,您并没有确切说明将 thie'console.log(this.state.items)' 行放在哪里。如果它是在 setState 调用之后立即进行的,那么在 console.log 命令之前可能还没有完成状态。
    • 您可能需要确保您也正确解析了响应。修改见代码示例
    • 请注意setState - 状态更新可能是异步的 - reactjs.org/docs/…
    • 同意。推断如上。
    猜你喜欢
    • 2019-12-11
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多