【发布时间】:2020-12-05 12:20:10
【问题描述】:
我这里有这段代码。我不断收到错误消息:
TypeError:无法读取未定义的属性“地图”。
以下是一些事实:
- 我从前端 javascript 文件中获取数据。所以不应该有任何异步问题。
-
singleCategory.title始终正确显示。 - 只有当我刷新页面时才会发生错误。如果我注释掉地图代码并添加代码。这样 React 就可以在不刷新的情况下注入它。有用。如果我刷新页面或尝试导航到它,我只会收到错误。
为什么singleCategory.title 显示正确但使用地图未定义?此外,地图仅在刷新时未定义。如果代码被注入,它就可以正常工作。
const CoursesCategories: React.FC = () => {
const [singleCategory, setSingleCategory] = useState<CategoriesInterface>([] as any);
useEffect(() => {
const fullUrl = window.location.href;
const segments = new URL(fullUrl).pathname.split('/');
const id = segments.pop() || segments.pop();
for (let category of Categories ) {
if (category.url === id) {
setSingleCategory(category);
console.log(singleCategory)
}
}
}, [singleCategory]);
return (
<div>
{
singleCategory.courses !== [] ? (
<div>
<CategoryTitle title={singleCategory.title} />
<div className={wrapper.headerWrapper}>
{
singleCategory.courses.map((course: CoursesInterface) => (
<h2 key={course.id}>{course.title}</h2>
)
)
}
</div>
</div>
) : ''
}
</div>
)
}
编辑 1. 如果我这样写,我明白了。
无法读取未定义的属性“长度”
{ singleCategory.courses.length > 0 && singleCategory.courses.map((course: CoursesInterface) => (
<h2 key={course.id}>{course.title}</h2>
)
)}
【问题讨论】:
-
useEffect在第一次渲染之后运行,因此未在该渲染上定义 singleCategory。通常有条件地渲染地图,它会在第二次渲染时使用获取的数据进行渲染。 -
将条件渲染添加到您的 .map()
{ singleCategory.courses.length > 0 && singleCategory.course.map(...)}
标签: javascript reactjs typescript