这是我正在使用的“数据库”,
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文件中,将executionPlan的属性传递给我的Workout.js子级。
WorkoutPlan.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文件中,我试图仅映射WorkoutPlan.workout.exercises的Exercises属性。但是,当我运行此代码时,我遇到了 TypeError:无法读取未定义的属性“练习”
这个孩子我在做什么错事?
Workout.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文件中
答案 0 :(得分:2)
在第一个渲染中,传递给props.workout
的{{1}}值为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>
);
});
}
的{{1}}值。