【问题标题】:Fetching and Displaying data from multi-dimension array repeatedly in React在 React 中重复从多维数组中获取和显示数据
【发布时间】:2019-08-31 02:23:31
【问题描述】:

我从 PostgresSQL 服务器获取数据并将它们放入数组中:

var that = this;
var temp = [];
await fetch(req)
  .then(function(res) {
    res.json().then(function(data) {
      for (var i in data) {
        temp.push([
          data[i].flavor
          data[i].addons,
          data[i].price
        ]);
      }
      that.setState({
        thatArray: temp
      });
    });
  })

console.log(this.state.thatArray);

console.log(this.state.thatArray) 的结果是这样的

https://i.imgur.com/tO9Uszz.jpg

我想以这种形式重复显示数据直到数组结束(下图示例)

<div className="row-container">
  <div className="flavor-name">
    <div>Milk</div>
  </div>

  <div className="add-tab">Add</div>

  <div className="add-tab-list">
    <li>- Cereal</li>
    <li>- Red Jelly</li>
    <li>- Peach</li>
    <li>- Honey Star</li>
  </div>

  <div className="price-text" style={{ textAlign: "right", marginRight: "20px" }}>
    40 USD
  </div>
  <hr />
</div>

示例结果:(https://i.imgur.com/oFaEQfa.jpg)

我之前使用过array.map(),但只有一个数组来完成列表。当我试图让它与这种数组一起工作时,这非常令人困惑。 有没有简单的数据展示方式?


编辑:Phix 建议的渲染方法效果很好。但是我还是有数组的问题。

这是我的componentWillMount() 和getProducts()

componentWillMount() {
    this.setState({
       bag: getProducts()
    });
}

function getProducts() {
  let uid = {
    userID: localStorage.getItem("user")
  };

  var req = new Request("/user/order", {
    method: "POST",
    headers: new Headers({
      "Content-Type": "application/json",
      Accept: "application/json"
    }),
    body: JSON.stringify(uid)
  });

  var temp = [];

  fetch(req)
    .then(function(res) {
      res.json().then(function(data) {
        for (var i in data) {
          temp.push([
            data[i].flavor,
            data[i].addons,
            data[i].price
          ]);
        }
      });
    })
    .catch(function(err) {
      console.log(err);
    });

  console.log(temp);


  return temp;

  //return [
  //  ["Milk", ["Item 1", "Item 2", "Item 3"], "40"],
  //  ["Charcoal", ["Item 1a", "Item 2a", "Item 3a"], "45"],
  //  ["Ham", ["Item 1b", "Item 2b", "Item 3b"], "30"]
  //];
}

问题是它只有在我直接声明返回的数组时才有效。

return [
["Milk", ["Item 1", "Item 2", "Item 3"], "40"],
["Charcoal", ["Item 1a", "Item 2a", "Item 3a"], "45"],
["Ham", ["Item 1b", "Item 2b", "Item 3b"], "30"]
];

当我返回 temp 数组时它不起作用。屏幕上什么也没显示。

return temp;

我注意到数组不同。

https://i.imgur.com/Z4SGtHZ.png

两个数组的图片中的第一行不一样。上面的一个是从获取的响应中得到的数组,下面的一个是手动输入的。

编辑:我发现控制台是live,第一次调用时内容是空的,所以第一行看起来是空的。但是,仍然无法弄清楚我的问题。

另外,当返回 temp 时,引用 bag[0] 什么都没有,bag[0][1] 将导致 Uncaught TypeError: Cannot read property '1' of undefined 而当 getProducts() 返回手动键入的数组时一切正常。


编辑:我尝试在加载所有内容后稍后单击按钮上的this.setState({ bag: this.state.bag });,并且所有数据都出现了。自从页面最初加载以来,有什么办法可以做到这一点?

【问题讨论】:

标签: javascript arrays reactjs postgresql


【解决方案1】:

有一些“更严格”的方法,但这里有一个想法可以帮助您入门:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      bag: []
    };
  }

  componentWillMount() {
    this.setState({
      bag: getProducts()
    })
  }

  render() {
    const { bag } = this.state;

    const renderTitle = (index) => {
      return <h1>{bag[index][0]}</h1>
    }

    const renderItems = (index) => {
      const items = bag[index][1]
      return (
        <ul>
          {items.map(item => <li>{item}</li>)}
        </ul>
      )
    }

    const renderPrice = (index) => {
      return <div>{bag[index][2]}</div>
    }

    return (
      bag.map((group, index) => {
        return (
          <div>
            {renderTitle(index)}
            {renderItems(index)}
            {renderPrice(index)}
          </div>
        )
      })
    );
  }
}

render(<App />, document.getElementById('root'));

function getProducts() {
  return [
    ['Milk', ['Item 1', 'Item 2', 'Item 3'], '40'],
    ['Charcoal', ['Item 1a', 'Item 2a', 'Item 3a'], '45'],
    ['Ham', ['Item 1b', 'Item 2b', 'Item 3b'], '30'],
  ]
}

Stackblitz

编辑:

temp 如此返回的原因是它最初被视为一个空数组,但一旦 fetch 解决,它将显示您所期望的。

var temp = [];            // [0] Start empty
fetch(req).then(() => {   // [1] Fire off async request and continue with event loop
  // ...                     [4] Once this resolves, temp gets populated
})
console.log(temp); //        [2] Event loop continues to here, showing empty array
return temp; //              [3] Nothing here

或者,使用异步/等待:

var temp = [];                   // [0] Start empty
const results = await fetch(req);// [1] Wait for async request and continue
console.log(temp);
return temp;                        [2] As expected

我已经使用虚假请求更新了 stackblitz 以呈现异步数据。

【讨论】:

  • 谢谢!这太棒了。它确实帮助我显示数据。我在获取数组时仍然遇到问题,你能看看我在主帖中编辑的问题吗?
  • 天啊,它就像魅力一样。真是太感谢你了!
猜你喜欢
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 2017-05-15
  • 2019-11-04
  • 2016-02-13
  • 1970-01-01
相关资源
最近更新 更多