为什么 this.state 数组的第一个值未定义?反应

问题描述 投票:0回答:1


import React, {Component} from "react"
import './index.css';

export default class ListArticle extends Component {
    constructor(props) {
        super(props);
        this.state = {
            arrayJson: [""],
        }
    }
    get() {
        fetch("http://localhost:8080/getHeaders", {
            method: "GET"
        })
            .then(data=>data.json())
            .then((data)=>{
                    this.setState({arrayJson:data.headerArray})
                }
            )
    }

    componentDidMount() {
        this.get();
        for(let i=0;i<4;i++) {
            let n="";
            let header = this.state.arrayJson[i];
            let t=true;
            for (let j = 0; j < 120; j++) {

                n += header[j];
                if (n === header) {
                    t = false;
                    break;
                }
            }
            if (t) {
                n += "...";
                console.log(n);
            } else {
                console.log(n);
            }
        }
    }


    render() {

        return (

            <div id={"container"}>

            </div>
        );
    }
}

这是我的listArticle类

我需要获取字符串值列表

s and after this I check every element and if the element length is more than 120 symbols i stop to read string element and add "..." to element
然后将其放在console.log上

但问题是浏览器的控制台向我显示了这个

enter image description here

它也给了我
enter image description here
据我所知,事实是第一个元素未定义,或者列表没有时间初始化,我还没弄清楚

如果您只是尝试在初始化后输出列表:

import React, {Component} from "react"
import './index.css';

export default class ListArticle extends Component {
    constructor(props) {
        super(props);
        this.state = {
            arrayJson: [""],
        }
    }
    get() {
        fetch("http://localhost:8080/getHeaders", {
            method: "GET"
        })
            .then(data=>data.json())
            .then((data)=>{
                    this.setState({arrayJson:data.headerArray})
                }
            )
    }

    componentDidMount() {
        this.get();

    }


    render() {

        return (

            <div id={"container"}>
                {console.log(this.state.arrayJson)}
            </div>
        );
    }
}

控制台给出了这个:enter image description here
怎么了?

reactjs state
1个回答
0
投票

所以 componentDidMount 仅在组件安装时调用一次,因为您只运行一次逻辑,状态为 arrayJson: [""]。您将从 header[j] 的串联值中获取未定义的值,其中 i 等于 0,使 header 的值为“”。这是因为 header[0…120] 的索引不存在于字符串“”中。

在此之后,您将得到一个异常,因为 arrayJson: [""] 只有一个元素 (arrayJson[0]),导致 i 增至 1,导致 header 等于未定义。 header[0] 会给你一个异常,因为 header 未定义。

之所以能看到I.render函数是因为每次state或者parent发生变化时render都会重新运行……

我建议在这里查看一下 React 的类生命周期函数 https://react.dev/reference/react/Component :)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.