当前位置: 代码迷 >> JavaScript >> 不理解未捕获的Typerror无法读取未定义的0属性?
  详细解决方案

不理解未捕获的Typerror无法读取未定义的0属性?

热度:25   发布时间:2023-06-13 11:50:06.0

创建我的第一个ReactJS网站并在后端中使用Node,目前在下面的代码中,我将获取数据,然后将其打印在页面上。 我设法从服务器中打印项目中人员的姓名,他们的照片和他们的电子邮件,但是出现该项目的描述,但出现错误:

TypeError:无法读取未定义的属性“ 0”

我不明白。

这是代码:

class ProjectPage extends Component {
constructor(props) {
    super(props);
    this.state = {
        user: [],
        description: [],
        mail: [],
        name: [],
    };
    this.getNames = this.getNames.bind(this);
    this.getPictures = this.getPictures.bind(this);
    this.getMails = this.getMails.bind(this);
    this.getDetails = this.getDetails.bind(this);
}

我创建了类和所有必需的元素

componentDidMount() {
    console.log("BEGIN componentDidMount");
    this.fetchDetails();
    this.fetchNames();
    this.fetchMails();
    console.log("END componentDidMount");
}

调用我的componentDidMount()中的所有函数

fetchDetails() {
    console.log("BEGIN fetchDetails()");

    let url = 'http://192.168.1.33:8080/getprojectdetails/Aprite';
    console.log("url details = " + url);

    fetch(url)
        .then(results => {
            var json = results.json();
            return json;
        })

        .then(data => {
            this.setState({ description: data });
        })

    console.log("END fetchData()");
}

这是项目描述的获取

getDetails = () => {
    let lines = [];
    let nbr = this.state.description.length;
    console.log("nbr = " + nbr);
    if (nbr){
        console.log("lines = " + this.state.description[0].P_Description);
        for (let i = 0; i < nbr; i++)
            lines.push(<div key={this.state.descripton[i].P_Description}></div>);
    }
    return (lines);
}

以及在Render()函数中打印数据的函数

但是,当我尝试打印此数据时,nbr的值从0传递到1,然后再次传递到0 ...在控制台日志中,我可以看到说明,但它没有出现在网站上,我也看不到。

请帮我 ?

getDetails函数内部循环中有一个错字
您应该编写this.state.description而不是this.state.descripton

希望这能解决您的问题:)

因此,在React渲染生命周期系统中, componentDidMount实际上将第一次渲染之后发生。 在第一个渲染期间,您尝试访问空数组的第一个元素,这是您看到的错误。

为了解决此问题,在您的render方法中,当我们等待fetchDetails从服务器返回值时,您应该准备一个后备的东西来渲染。 如果您不希望其呈现任何内容,则可以return null

即。

const { description = [] } = this.state;
if (description.length === 0) {
    return null;
}
return this.getDetails();

附带说明一下,为了避免所有这些(变得很难维护):

this.getNames = this.getNames.bind(this);
this.getPictures = this.getPictures.bind(this);
this.getMails = this.getMails.bind(this);
this.getDetails = this.getDetails.bind(this);

您可以将它们定义为类属性,如下所示:

getNames = () => {
   // do stuff
}
  相关解决方案