reactjs - 无法在映射函数内的 React JS 中读取未定义的属性“substr”
问题描述
在尝试渲染功能组件并尝试使用item.biography.substr(0, 20)
.
我尝试了不同的语法但没有成功。将不胜感激任何帮助。这是我的组件。
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from 'axios';
import $ from 'jquery';
//import "./styles.css";
function Instructor() {
const [page, setPage] = useState(1);
const [data, setData] = useState(['a', 'b', 'c']);
const [isLoading, setIsLoading] = useState(true);
const loadMoreData = () => {
setPage(page + 1);
};
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'http://www.localhost/ulearn/api/getInstructors',
);
setData(result.data);
};
fetchData();
}, []);
return (
<div>
<h1> API FOR INSTRUCTOR COMPONENT </h1>
{isLoading && <p>Wait I'm Loading comments for you</p>}
{data.length !== 0 && (
<button onClick={loadMoreData}>Load More Data</button>
)}
{data.map((item, index) => (
<div className="col-xl-3 col-lg-4 col-md-6 col-sm-6" key={index}>
<div className="instructor-box mx-auto text-center">
<a href="{{ route(d.view, d.instructor_slug) }}">
<main>
<div className="col-md-12">
<h6 className="instructor-title">{item.first_name}
{item.last_name}
`enter code here`</h6>
<p> {item.biography.substr(0, 20)} </p>
</div>
</main>
</a>
</div>
</div>
))}
</div>
);
}
if (document.getElementById('instructor')) {
ReactDOM.render(<Instructor />, document.getElementById('instructor'));
}
解决方案
似乎它正在尝试在undefined
属性上运行 substring 方法?这可能意味着它biogarphy
可能是未定义的。
鉴于 的初始状态data
是['a', 'b', 'c']
,可以肯定的biography
是undefined
在等待来自钩子的响应fetchData()
时。useEffect()
在这种情况下,您可能希望进行空/未定义检查,并仅在已填充来自钩子的响应时才使用该substr()
方法有条件地运行该语句item.biography
useEffect
{item.biography && item.biography.substr(0, 20)}
推荐阅读
- android - 数据已添加到数据库中,但无法从中加载。安卓
- node.js - 如果我在 Heroku 或其他托管平台上托管我的 nodejs 应用程序,我可以忽略使用 HTTPS 为我的应用程序提供服务吗?
- c# - C# WinForms 表单计时器不在循环内滴答作响
- swift - 在 tableview 搜索文本结果中显示匹配的文本
- matlab - 在 Matlab 中创建 tf 对象数组
- microsoft-cognitive - 不能以编程方式训练“自定义翻译器”吗?
- python - 用于进行更改的分而治之的递归解决方案
- python - 合并具有依赖关系的重叠区间对象
- r - 按因子计算索引组并使用 ggplot 绘图
- ag-grid-react - 如何更改复选框颜色?AG网格