无法渲染对象值

时间:2018-05-12 10:53:33

标签: reactjs

我尝试渲染表格,但是我收到了渲染错误,我查看了其他堆栈的问题,并建议我应该使用map来返回对象数组值。我也在地图中使用了渲染。我的对象看起来像这样:

[
    {
        amount_left: "100",
        category: "vegtable",
        food_name: "potatos",
        price: "1",
        type: "salty"
    }, 
    {
        amount_left: "100",
        category: "cheese",
        food_name: "cheese",
        price: "0.5",
        type: "salty"
    },
    ...
]

我的代码。

 import React, { Component } from 'react';
    import { Table } from 'reactstrap';


    class Meals extends Component {

       getMeals = async () =>{
        const api_call = await fetch(`http://127.0.0.1/RFIDSys/rfid_handler.class.php?action=getAllMeals`);
        const data = await api_call.json(); 
        console.log(data[0].food_name) //  returns potatos
        return data.map((item,i) => {
           return (<tr><td>{item.food_name}</td></tr>)
          })
      }

      render(){
        return (
        <div>
          <Table>
            <tbody>
          {this.getMeals()}
            </tbody>
          </Table>
        </div>
        );  
    }

    }


      export default Meals;

看不出有什么不对,我得到了#34;对象作为React孩子无效(找到:[object Promise])。如果你打算渲染一个孩子们,改用阵列。&#34;错误。

建议使用数组的错误,我在地图功能中使用数组,或者它仍然是我回归的对象?

1 个答案:

答案 0 :(得分:1)

您的渲染功能是同步功能。但是,getMeals函数是异步函数。 Async-await关键字将您的函数包装成promise,因此getMeals函数会向您的渲染函数返回一个承诺,因此您无法在渲染函数中使用getMeals。 您可以使用州来解决您的任务:

&#13;
&#13;
import React, { Component } from "react";
import { Table } from "reactstrap";

class Meals extends Component {
  state = { meals: null };
  componentDidMount() {
    this.loadMeals();
  }

  loadMeals = async () => {
    const api_call = await fetch(
      `http://127.0.0.1/RFIDSys/rfid_handler.class.php?action=getAllMeals`
    );
    const data = await api_call.json();
    console.log(data[0].food_name);
    this.setState({ meals: data });
  };

  render() {
    if (!this.state.meals) {
      return null;
    }
    return (
      <div>
        <Table>
          <tbody>
            {this.state.meals.map((item, i) => (
              <tr>
                <td>{item.food_name}</td>
              </tr>
            ))}
          </tbody>
        </Table>
      </div>
    );
  }
}

export default Meals;
&#13;
&#13;
&#13;