【问题标题】:how to render a react component for every item in JSON file?如何为 JSON 文件中的每个项目呈现一个反应组件?
【发布时间】:2020-07-28 23:35:09
【问题描述】:

我想构建锻炼应用程序,所以我创建了一个 JSON 文件,其中包含“exerciseName”和“discription”(我只是在玩 react)

首先我创建了一个名为“ExerciseCard”的组件

  import React from 'react'

function ExerciceCard(props) {

        return(
            <h1>this is the exercie {props.exerciceName}</h1>
        )
}


export default ExerciceCard

然后我创建了一个名为 CreateNewWorkout 的页面

import React from 'react'
import ExerciseCard from '../component/ExerciseCard'

class CreateNewWorkout extends React.Component {
    state = {
        exercises : []
    }

    async    componentDidMount() {

        let response  = await fetch("http://localhost:1337/calisthenics-exercices")
        const data =  await response.json()
//i wanted to loop throgh the array of and push the exerciceName to the exercise state array
        for (let i = 0; i <data.lenght; i++) {
            this.setState({exercices : [...this.state.exercises, data[i].exeriseName]})
        }

    }
    render() {
        return(
            <>
            <ExerciseCard exerciceName = {this.state.exercice} ></ExerciseCard>
            </>
        )
    }

}

export default CreateNewWorkout

目前我在 JSON 文件中有两个“练习”,我想知道如何两次渲染 ExerciseCard 组件(在这种情况下)。

【问题讨论】:

    标签: reactjs components rendering state


    【解决方案1】:

    通常是这样的

    <div>
      {dataAsArray.map(val, i) => (
        <div key={i}>{val}</div>
      )}
    </div>
    

    所以,你需要

    <div>
     {this.state.exercice.map(ex, i) => (
       <ExerciseCard exerciceName={ex} key={i} />
     )}
    </div>
    

    注意:您在组件中的数据流是错误的 - 不适用于生产用途。

    【讨论】:

      【解决方案2】:

      很简单,你不能在一个循环中多次设置状态,而是首先将所有元素推入列表中,然后最后设置状态如下

      async    componentDidMount() {
              let response  = await fetch("http://localhost:1337/calisthenics-exercices");
              const data =  await response.json();
      const updatedState = [...this.state.exercise]
      data.forEach( item => updateState.push(item))
      setState({exercises : updatedState});
      

      然后为了渲染这个

          render() {
              return(
                  <div>
                      {this.state.exercise.map(item => <ExerciseCard exerciseName ={item} />)}
                  <div/>
              )
          }
      

      【讨论】:

      • 它会产生一个警告“数组或迭代器中的每个孩子都应该有一个唯一的“key”道具......”在您的解决方案中添加一个道具“key”以避免
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2019-04-28
      • 2017-07-11
      • 2017-08-20
      • 1970-01-01
      • 2020-01-01
      相关资源
      最近更新 更多