简体   繁体   English

列出未在React中呈现的元素

[英]List elements not rendering in React

This is my Sidebar component. 这是我的补充工具栏组件。

const Sidebar = React.createClass({
  render(){
    let props = this.props;
    return(
      <div className= 'row'>
      <h2>All Rooms</h2>
        <ul>
          {props.rooms.map((room, i) => {
            <li key={i}> {room.name} </li>
          })}
        </ul>
        {props.addingRoom && <input ref='add' />}
      </div>

    );
  }
})

This is where I render it populating one room. 这是我渲染它填充一个房间的地方。

ReactDOM.render(<App>
  <Sidebar rooms={[ { name: 'First Room'} ]} addingRoom={true} />
  </App>, document.getElementById('root'));

The contents inside the <ul></ul> tag don't render at all. <ul></ul>标记内的内容根本不呈现。 Any idea what I could be missing. 知道我可能缺少什么。

You aren't returning anything from the map function, so it renders nothing inside the unordered list. 您没有从map函数返回任何内容,因此它在无序列表中不呈现任何内容。 In your arrow function , you do: 在您的箭头功能中 ,您可以:

(room, i) => {
    //statements
}

This doesn't return anything. 这不会返回任何东西。 Array.prototype.map requires a callback that returns a value to do anything. Array.prototype.map需要一个返回值来执行任何操作的回调。 map transform elements to the array, mapping (executing) the callback on each element. map变换元素映射到数组, 映射 (执行)每个元素的回调。 The return value is what the value is in the corresponding position in the returned and mapped array. 返回值是返回和映射数组中相应位置的值。

You must return the list element in the map function like so: 您必须在map函数中返回list元素,如下所示:

<ul>
    {props.rooms.map((room, i) => {
      return <li key={i}> {room.name} </li>;
    })}
</ul>

Now, the mapped array of list elements is rendered because the list element is returned. 现在,呈现列表元素的映射数组,因为返回了list元素。

To make this shorter, you may write it in the form (params) => value which is equivalent to the above, where value is the returned value, like so: 为了缩短它,你可以用形式写(params) => value ,它等于上面的value ,其中value是返回值,如下所示:

{props.room.map((room, i) => <li key={i}> {room.name} </li>)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM