簡體   English   中英

Reactjs(javascript)我怎么看不到列表為空(之前)api 被調用

[英]Reactjs (javascript) how do I not see that the list is empty (Before) api gets called

這是當前代碼,當我加載列表頁面時,它顯示“未找到列表項目”,然后從后端 api 加載項目並顯示這些項目(上述消息消失)

import React, { Component } from 'react';

class List extends Component {

    // Initialize the state
    constructor(props){
        super(props);
        this.state = {
            list: [],
            isFetchedFromServer:false
        }
    }

    // Fetch the list on first mount
    componentDidMount() {
        this.getList();
    }

    // Retrieves the list of items from the Express app
    getList = () => {
        fetch('/api/getList')
            .then(res => res.json())
            .then(list => this.setState({ list }))
            .then(this.state.isFetchedFromServer= true)
    }

    render() {
        const { list } = this.state;

        return (
            <div className="App">
            <h1>List of Items</h1>
        {/* Check to see if any items are found*/}
        {list.length ? (
            <div>
            {/* Render the list of items */}
            {list.map((item) => {
                    return(
                        <div>
                        {item}
                        </div>
                );
                })}
            </div>
        ) : (
        <div className={((this.state.list != undefined) &&( this.state.list != null)) ? '' : 'hidden'}>
        <h2>No List Items Found</h2>
        </div>
        )
        }
    </div>
    );
    }
}

export default List;

我只想看到從后端調用空返回時沒有找到列表項。

請協助我這樣做。

聲明一個標志並在獲取完成后更新它。

this.isShowMessage: false;

componentDidMount() {
        this.getList();
        this.isShowMessage: (this.state.list == null);
    }

並相應地隱藏你的 div。

<div>
   {(this.isShowMessage) && <h2>No List Items Found</h2>}
</div>

由於 Api 是一個異步調用,它最初說列表是空的,在響應之后,列表中填充了對象。 您可能需要在 state 中添加一個 boolean APIProcessing ,初始值為 true,同時仍在從數據庫中獲取對象。 之后,您需要設置為 false 並顯示列表

你所面臨的一切都很好。 發生這種情況是因為您的應用程序可能需要很短的時間才能從 API 獲得響應。

因此,直到有響應,this.state.list 的長度將為 0。直到那個

未找到列表項

將顯示。

您可以否定該聲明以顯示它。

希望這可以幫助!

您缺少的是組件 state 中的 Boolean 標志“isLoading”。

在您的 componentDidMount 中,將其設置為 true。 提取完成后,將其設置為 false。

然后,僅顯示“未找到列表項”。 如果 isLoading 為 false 並且列表為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM