在React中使用.map()时处理空数组

Joh*_*Cdf 9 reactjs

我有一个React.JS组件,它将映射notes变量以显示.

但是,我遇到了没有笔记和收到错误的问题.什么是接近这个的正确方法?

这是代码:

import React, {Component} from 'react';


class List extends Component {
    constructor(props){
      super(props);
    }

render(){
  var notes = this.props.items.map((item, i)=>{
      return(
          <li className="listLink" key={i}>
              <p>{item.title}</p>
              <span>{item.content}</span>
          </li>
          )
      });
    return(
      <div className='list'>

          {notes}

      </div>
    );
  }
}

export default List;
Run Code Online (Sandbox Code Playgroud)

fou*_*ing 6

如果要在存在至少一个注释时渲染注释,而在数组中没有注释时要渲染默认视图,则可以将渲染函数的return表达式更改为:

return(
  <div className='list'>
      {notes.length ? notes : <p>Default Markup</p>}
  </div>
);
Run Code Online (Sandbox Code Playgroud)

由于JavaScript中的空数组是真实的,因此您需要检查数组的长度,而不仅仅是数组的布尔值。

请注意,如果您的itemsprop永远为null,则将导致异常,因为您将调用mapnull值。在这种情况下,我建议默认使用Facebook的prop-types库设置items为空数组。这样,如果items不设置,组件将不会损坏。


小智 6

这是最简单的处理方法

  import React, {Component} from 'react';


class List extends Component {
    constructor(props){
      super(props);
    }

render(){
  var notes = this.props.items?.map((item, i)=>{
      return(
          <li className="listLink" key={i}>
              <p>{item.title}</p>
              <span>{item.content}</span>
          </li>
          )
      });
    return(
      <div className='list'>

          {notes}

      </div>
    );
  }
}

export default List;
Run Code Online (Sandbox Code Playgroud)

只需尝试添加“?” 对于您映射的数组


Dim*_*gal 5

您可以只为 this.props.item

render() {
  const items = this.props.items || [] // if there's no items, give empty array
  const notes = items.map((item, i) => {
  return(
      ....
Run Code Online (Sandbox Code Playgroud)

.map()对空数组执行操作不会产生错误,但会返回一个空数组。这很好,因为空数组是 react 中的可渲染项,不会产生错误render(),也不会渲染注释,因为没有提供注释。