状态为null时,呈现器内是否出错?

时间:2018-11-27 07:13:22

标签: reactjs

我有一个简单的组件,用于初始化构造函数和函数中的状态

this.remove = this.remove.bind(this)
this.state = {
  lalo: this.Service.getObjects() //Array
};

在渲染方法中,我尝试验证lalo是否为空

render() {
    if (this.state.lalo !== null) {
      return (
        //Load if state has items, also pass the function to a child component which can remove items from this state.
      );
    } else {
      return <p>None.</p>;
    }
  }

还有一种从状态中删除项目的方法

remove = id => {
    this.setState(state => {
      var lalo = state.lalo.filter(item => item.id !== id);
      return {
        lalo
      };
    });
};

我遇到的问题是,当我从状态中删除所有项目时,render方法会引发未定义的错误,并且似乎不是呈现“ else”部分而是呈现真实条件。

1 个答案:

答案 0 :(得分:0)

您需要更新条件

  

this.state.lalo!==空

由于要删除所有元素,因此this.state.lalo = []不等于null,因此上述条件变为true,它将尝试呈现您的子组件,而不是文本None。

您可以将条件更新为

  

if(this.state.lalo && this.state.lalo.length> 0){...

或处理子组件中的空数组。