我想构建锻炼应用程序,因此我创建了一个具有“ exerciseName”和“ discription”的JSON文件(我只是在玩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
组件(在这种情况下)。
通常,它像下面这样
很简单,您不能在循环中多次设置State,而是先将列表中的所有元素都放入列表中,然后再按如下所示设置State)>
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});