[英]TypeError: Cannot read property 'map' of undefined is showing when I'm trying to map over the props passed from parent component to child component
[英]I'm getting a Cannot read property of 'exercises' of undefined error when trying to map my props
這是我正在使用的“數據庫”,
index.js:
const workoutPlan = {
ID: 1,
Name: "My Workout Plan",
workout: {
day: "Monday",
exercises: [
{
Name: "Bench Press",
sets: [
{
set: 1,
weight: 135,
rep: 10
},
{
set: 2,
weight: 145,
rep: 8
}
]
},
{
Name: "Deadlift",
sets: [
{
set: 1,
weight: 135,
rep: 10
},
{
set: 2,
weight: 145,
rep: 8
}
]
}
]
}
};
然后在我的 WorkoutPlan.js 文件中,我將鍛煉計划的屬性傳遞給我的 Workout.js 孩子。
鍛煉計划.js:
import React from "react";
import Workout from "./Workout";
import axios from "axios";
class WorkoutPlan extends React.Component {
constructor() {
super();
this.state = {
workoutPlan: {}
};
}
componentDidMount() {
axios
.get("/api/workout-plan")
.then(response => {
this.setState({ workoutPlan: response.data });
})
.catch(error => {
console.log(error);
});
}
render() {
const { workoutPlan } = this.state;
// const workoutPlan = this.state.workoutPlan;
return (
<div>
<h1>{workoutPlan.Name}</h1>
<Workout workout={workoutPlan.workout} />
</div>
);
}
}
export default WorkoutPlan;
在我的 Workout.js 文件中,我只嘗試 map WorkoutPlan.workout.exercises 的練習屬性。 但是,當我運行此代碼時,我遇到了 TypeError: Cannot read property 'exercises' of undefined
我在這個孩子身上做錯了什么?
鍛煉.js:
import React from "react";
import Exercise from "./Exercise";
// const Workout = props => {
// props.workout.exercises.map(exercises => {
// return (
// <div>
// <h2>"Workout for {props.day}"</h2>
// <Exercise exercises={exercises} />
// </div>
// );
// });
// };
function Workout(props) {
props.workout.exercises.map(exercises => {
return (
<div>
<h2>"Workout for {props.day}"</h2>
<p>{exercises.Name}</p>
<Exercise exercises={exercises} />
</div>
);
});
}
export default Workout;
我已經注釋掉了 const,因為有人告訴我它們都是可以互換的方法。 但是,如果有人真的可以提供一些關於如何在這兩種方法上做到這一點的見解,我將不勝感激。 該錯誤具體指
props.workout.exercises.map(exercises => {
在我的 Workout.JS 文件中
在第一次渲染時,傳遞給Workout
的props.workout
值是undefined
的,因為在父組件WorkoutPlan
中查看this.state.workoutPlan
的默認值是{}
,因此調用鍛煉計划workoutPlan.workout
將是“未定義的”。
有兩種方法,如果值為undefined
,則在父級中不渲染此組件。 或者,在孩子中,處理undefined
的值。
在父母中處理:
render() {
const { workout } = this.state.workoutPlan;
return (
<div>
<h1>{workoutPlan.Name}</h1>
{workout && <Workout workout={workout} />}
</div>
)
}
或者,在孩子身上:
function Workout(props) {
// Early return if falsy value is passed (eg: undefined, null)
if (!props.workout) return null;
return props.workout.exercises.map(exercises => {
return (
<div>
<h2>"Workout for {props.day}"</h2>
<p>{exercises.Name}</p>
<Exercise exercises={exercises} />
</div>
);
});
}
注意,您還需要return
props.workout.exercises.map
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.