反应检查为空

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

当我在React中构建我的第一个应用程序时,我在检查时遇到了一些困难。

这是构造函数

constructor() {
    super()
    this.state = {
      id: '',
      title: '',
      price: '',
      off_price: '',
      category_id: '',
      arttitle: '',
      artbody: '',
      shown: false,
      editDisabled: false,
      items: []
    }
    getAll = () => {
      const {
        categoryid
      } = this.props;
      getProducts(categoryid).then(data => {
        this.setState({
            title: '',
            price: '',
            off_price: '',
            category_id: this.props.categoryid,
            items: [...data]
          },
          () => {
            console.log(this.state.items)
          }
        )
      })
    }

这就是我列出所需内容的方式

{this.state.items.map((item, index) => ( 
... 
))}

现在我有一个简单的div,只有当this.state.items为空时才需要显示。

javascript reactjs
1个回答
0
投票

由于items已经被声明为状态中的数组,因此您可以简单地测试长度:

render() {

  if (!this.state.items.length) return <div>Items is null</div>

  return (
    <div>
      {this.state.items.map((item, index) => {...}
    </div>
  );

}
© www.soinside.com 2019 - 2024. All rights reserved.