提问人:Abhishek 提问时间:11/7/2023 更新时间:11/7/2023 访问量:48
我收到错误 - TypeError:在 react.js 项目的 UI 中渲染组件时无法读取未定义的属性(读取“map”)
I am getting an error - TypeError: Cannot read properties of undefined (reading 'map') while rendering the component in the UI in a react.js project
问:
我在这里粘贴了“锻炼”组件,该组件在UI中呈现数据,但抛出错误。
import React from 'react';
import { Container, Typography, Paper, Grid, List, ListItem, ListItemText } from '@mui/material';
import { useLocation } from 'react-router-dom';
const Workout = () => {
const location = useLocation();
const { workoutPlan } = location.state;
if (!workoutPlan) {
return null;
}
const renderDays = (days) => {
return days.map((day, index) => (
<Grid item xs={12} key={index}>
<Typography variant="h6">Day {index + 1}</Typography>
<List>
{day.excercises.map((exercise, exerciseIndex) => (
<ListItem key={exerciseIndex}>
<ListItemText
primary={`${exercise.name} (${exercise.target_muscle})`}
secondary={`Reps: ${exercise.reps}, Sets: ${exercise.sets}`}
/>
</ListItem>
))}
</List>
<Typography variant="subtitle1">Duration: {day.duration} minutes</Typography>
</Grid>
));
};
return (
<Container maxWidth="md">
<Typography variant="h4">Your Personalized Workout Plan</Typography>
<Paper style={{ padding: '16px' }}>
<Typography variant="h6">Workout Plan Description</Typography>
<Typography>{workoutPlan.Workout_Plan_Description}</Typography>
{workoutPlan.Months.map((month, monthIndex) => (
<div key={monthIndex}>
<Typography variant="h5">Month {monthIndex + 1}</Typography>
{renderDays(month.plan_for_each_week_in_the_month.days)}
</div>
))}
</Paper>
</Container>
);
};
export default Workout;
我还在这里粘贴了“主页”组件。
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Container, TextField, Button, Typography, CircularProgress } from '@mui/material';
import Select from 'react-select';
import { useNavigate } from 'react-router-dom';
const genderOptions = [
{ value: 'male', label: 'Male' },
{ value: 'female', label: 'Female' },
];
const fitnessLevelOptions = [
{ value: 'begineer', label: 'Beginner' },
{ value: 'intermediate', label: 'Intermediate' },
{ value: 'advanced', label: 'Advanced' },
];
const targetMusclesOptions = [
{ value: 'upper body', label: 'Upper Body' },
{ value: 'lower body', label: 'Lower Body' },
{ value: 'core', label: 'Core' },
];
const durationOptions = [
{ value: '15', label: '15 minutes' },
{ value: '30', label: '30 minutes' },
{ value: '45', label: '45 minutes'},
{ value: '60', label: '60 minutes'},
];
const HomePage = () => {
const [userData, setUserData] = useState({
age: '',
gender: [],
fitnessLevel: [],
targetMuscles: [],
duration: [],
});
const [workoutPlan, setWorkoutPlan] = useState('');
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const handleGenerateWorkoutPlan = async () => {
setLoading(true);
const TOKEN = 'YOUR_API_KEY';
const topic = `give me a weekwise fitness plan with exercises for the following parameters
${JSON.stringify(userData)}
in the form of a json schema like this
{
"Workout_Plan_Description":"200 letters max",
"Months" : [
{
"plan_for_each_week_in_the_month":
{
"days":[
{
"excercises": [
{
"name": "",
"reps":"",
"sets":"",
"target_muscle":""
}
],
"duration": 30
}
]
}
}
]}. Make sure to split the muscle groups throughout the week`;
try {
const response = await axios.post(
"https://api.openai.com/v1/engines/text-davinci-003/completions",
{
prompt: topic,
max_tokens: 3500,
n: 1,
stop: null,
temperature: 0,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
},
{
headers: {
'Authorization': `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
}
);
const responseData = response.data;
setWorkoutPlan(responseData.choices[0].text);
navigate('/workout', { state: { workoutPlan: responseData.choices[0].text } }); // Use navigate to go to the WorkoutPlan page
} catch (error) {
console.error('Error generating workout plan:', error);
} finally {
setLoading(false);
}
};
return (
<Container maxWidth="sm">
<Typography variant="h4">AI Workout Generator</Typography>
<TextField
label="Age"
fullWidth
value={userData.age}
onChange={(e) => setUserData({ ...userData, age: e.target.value })}
/>
<Select
options={genderOptions}
value={userData.gender}
onChange={(selected) => setUserData({ ...userData, gender: selected })}
placeholder="Select Gender"
/>
<Select
options={fitnessLevelOptions}
value={userData.fitnessLevel}
onChange={(selected) => setUserData({ ...userData, fitnessLevel: selected })}
placeholder="Select Fitness Level"
/>
<Select
options={targetMusclesOptions}
isMulti
value={userData.targetMuscles}
onChange={(selected) => setUserData({ ...userData, targetMuscles: selected })}
placeholder="Select Target Muscles"
/>
<Select
options={durationOptions}
value={userData.duration}
onChange={(selected) => setUserData({ ...userData, duration: selected })}
placeholder="Select Duration"
/>
<Button variant="contained" color="primary" onClick={handleGenerateWorkoutPlan}>
Generate Workout Plan
</Button>
{loading && <CircularProgress style={{ marginTop: '16px' }} />}
</Container>
);
};
export default HomePage;
我正在尝试渲染组件“Workout”中存在的数据,该组件通过 OpenAI API 从“HomePage”组件接收 JSON 数据,但在 Workout 组件中将接收的 JSON 数据转换为人类可读的格式时抛出错误。提交数据后出错任何帮助将不胜感激。
答: 暂无答案
评论
.map()
在所示代码中的三个位置使用。哪一个抛出错误?哪个值是?你期望它有什么价值,为什么?undefined
days
day.excercises
workoutPlan.Months
month.plan_for_each_week_in_the_month.days