gpt4 book ai didi

javascript - Reactjs(javascript)我怎么看不到列表为空(之前)api被调用

转载 作者:行者123 更新时间:2023-12-02 22:35:26 25 4
gpt4 key购买 nike

这是当前的代码,当我加载列表页面时,它会暂时显示“未找到列表项目”,然后它会从后端 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>

关于javascript - Reactjs(javascript)我怎么看不到列表为空(之前)api被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58761882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com