在React中重复从多维数组中获取和显示数据

问题描述 投票:0回答:1

我从PostgresQL服务器获取数据并使用以下方法将它们放入数组中:

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个回答
0
投票

有“更严格”的方式,但这是一个有希望让你开始的想法:

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回归的原因是它最初被视为一个空数组,但一旦获取结果,它将显示你所期待的。

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

或者,使用async / await:

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以呈现异步数据。

© www.soinside.com 2019 - 2024. All rights reserved.