首页 > 解决方案 > 无法在映射函数内的 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'));
}

标签: reactjsdictionaryundefinedrendersubstr

解决方案


似乎它正在尝试在undefined属性上运行 substring 方法?这可能意味着它biogarphy可能是未定义的。

鉴于 的初始状态data['a', 'b', 'c'],可以肯定的biographyundefined在等待来自钩子的响应fetchData()时。useEffect()

在这种情况下,您可能希望进行空/未定义检查,并仅在已填充来自钩子的响应时才使用该substr()方法有条件地运行该语句item.biographyuseEffect

{item.biography && item.biography.substr(0, 20)}

推荐阅读