React中表空时显示无结果

时间:2018-05-09 11:59:16

标签: arrays reactjs

我有一个显示联系信息的行表。当listItems数组为0时,我想让它呈现“无联系人”的混乱。我尝试创建一个const noEntries变量并将数组设置为0,并使用{noEntries No条目},但这是一个错误。

class ContactList extends Component {
  constructor(props) {
    super(props);

    this.createContact = this.createContact.bind(this);
  }

  delete(key) {
    this.props.delete(key);
  }

  createContact(item) {
    return  <tr key={item.key}>
              <td>{item.firstname}</td>
              <td>{item.lastname}</td>
              <td>{item.phone}</td>
              <td><i className="fas fa-trash-alt" onClick={() => { if (window.confirm('Are you sure you want to delete ' + item.firstname + ' ' + item.lastname + ' from your contacts?')) this.delete(item.key)}}></i></td>
            </tr>
  }

  render() {
    const contactEntries = this.props.entries;
    const listItems = contactEntries.map(this.createContact);
    return (
      <table className="mui-table mui-table--bordered">
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Phone</th>
          </tr>
        </thead>
        <tbody>
          {listItems}
        </tbody>
      </table>
    );
  }
};

export default ContactList;

2 个答案:

答案 0 :(得分:0)

render()中的

是这样的:

render() {
    const contactEntries = this.props.entries;
    const listItems = contactEntries.map(this.createContact);
    return (
      contactEntries.length > 0?
      <table className="mui-table mui-table--bordered">
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Phone</th>
          </tr>
        </thead>
        <tbody>
          {listItems}
        </tbody>
      </table>:<span>No results</span>
    );
  }

答案 1 :(得分:0)

使用三元运算符检查contactEntries中的记录数量length ==0然后return没有数据组件return rows

        const listItems = contactEntries && contactEntries.length >0 
                        ?  contactEntries.map(this.createContact) 
               : <tr key={item.key}>
                  <td rowspan="3">No data</td
                </tr>