React组件不会显示函数的返回

时间:2019-03-21 01:40:32

标签: javascript arrays reactjs state render

我有一个组件,该组件应该显示“卡片”,其中包含状态保存在数组中的信息。我从JSON文件中获取此信息,并将其保存到“ componentDidMount”中的数组中。然后,在返回渲染函数之前,我创建了一个名为“ displayFood”的函数,然后在返回函数中使用了该函数。问题是当我运行代码时,没有显示卡。

import React from 'react'
import "./style.scss";
import FoodData from "./foodData.json";

class Food extends React.Component {
    constructor(props){
        super(props);
        this.state={
            foodData: []
        }
    }

    componentDidMount(){
        FoodData.map((foodItem,index) => {
            var foodTemp = {
                id: index,
                name: foodItem.name,
                pic: foodItem.pic,
                serving: foodItem.serving,
                calories: foodItem.calories,
                sugar: foodItem.sugar,
                protien: foodItem.protien
            }
            this.setState((prevState) => {
                prevState.foodData.push(foodTemp)
            })
        })
    }

  render() {

    const displayFood = () => {
        var i;
        for(i = 0; i < this.state.foodData.length; i++){
            return(
                <div className="food-card">
                    <img src={require(`${this.state.foodData[i].pic}`)}/>
                    <ul>
                        <li>{this.state.foodData[i].name}</li>
                        <li>Serving: {this.state.foodData[i].serving}</li>
                        <li>Calories: {this.state.foodData[i].calories}</li>
                        <li>Sugar: {this.state.foodData[i].sugar}</li>
                        <li>Protien: {this.state.foodData[i].protien}</li>
                    </ul>
                    <button name={this.state.foodData[i].name}>Add</button>
                </div>
            )
        }
    }

      return(
        <div>
            <div className="food-container">
            {
                displayFood()       
            }
            </div>
        </div>
      )
  }
}

export default Food;

4 个答案:

答案 0 :(得分:2)

首先,我不确定setState中的componentDidMount是否工作。如果不想返回新数组,则不应使用map,而应使用forEach。您直接改变了状态,不建议这样做。该函数应如下所示:

componentDidMount(){
  // Build a new array of object from FoodData
  const newFoodData = 
        FoodData.map(({name, pic, serving, calories, sugar, protien }, index) => 
                     ({ id: index, name, pic, serving, calories, sugar, protien }))
  // Assign the new object to state
  this.setState({ foodData: newFoodData })
}

第二,return循环中的for仅返回第一项。您应该创建一个数组,然后将项目通过循环而不是返回

const displayFood = () => {
    let cards = [] // Crate an array
    for(let i = 0; i < this.state.foodData.length; i++){
        cards.push( // push item to array through the loop
            <div className="food-card">
                <img src={require(`${this.state.foodData[i].pic}`)}/>
                <ul>
                    <li>{this.state.foodData[i].name}</li>
                    <li>Serving: {this.state.foodData[i].serving}</li>
                    <li>Calories: {this.state.foodData[i].calories}</li>
                    <li>Sugar: {this.state.foodData[i].sugar}</li>
                    <li>Protien: {this.state.foodData[i].protien}</li>
                </ul>
                <button name={this.state.foodData[i].name}>Add</button>
            </div>
        )
    }
  return cards  // Return the array
}

我建议您将displayFood移动到render()函数之外。因为当其他原因导致重新渲染而不引起this.state.foodData更改时,组件必须重新构建displayFood()。那太浪费了。

答案 1 :(得分:0)

根据生命周期,render方法实际上已经在componentDidMount之前被调用。因此,到渲染时,数据仍然为空。为什么不在componentWillMount中移动数据初始化?

答案 2 :(得分:0)

尝试更改以前的状态...您直接使用状态数据,而不会更改状态根:

this.setState((prevState) => ({
    ...prevState,
    foodData: [ ...foodData, foodTemp ],
}))

答案 3 :(得分:0)

class Hello extends React.Component {

    constructor(props){
    super(props);
    this.state={
      foodData: []
    }
  }

  componentDidMount(){
    const  { foodData } = this.state;

    foodData.push({
        id: 0,
      name: 'beans',
      pic: 'picurl',
      serving: '2',
      calories: '100',
      sugar: '30',
      protien: '10'
    });

    this.setState({ foodData });

  }

  render() {
    return <div>
      <div className="food-container">
        {
          this.state.foodData.map((item,key) => {
            return <div className="food-card">
              {`${item.pic}`}
              <ul>
                <li>{item.name}</li>
                <li>Serving: {item.serving}</li>
                <li>Calories: {item.calories}</li>
                <li>Sugar: {item.sugar}</li>
                <li>Protien: {item.protien}</li>
              </ul>
              <button name={item.name}>Add</button>
            </div>
          })     
        }
      </div>

    </div>;
  }
}

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);


确保将foodData正确加载到“ componentDidMount()”上

https://jsfiddle.net/leolima/L7c418kp/13/