首页 > 解决方案 > 在 React 中显示项目列表

问题描述

我有一个简单的购物清单组件来显示状态中的项目

如何使用 ul 列表执行此操作

这是我的代码

我在 items.map 周围遇到错误,它说它期待一个:

import React, {Component} from 'react'
import uuid from 'uuid';

class ShoppingList extends Component {
    state = {
        items:[
            {id: uuid(), name: 'Eggs'},
            {id: uuid(), name: 'Bacon'},
            {id: uuid(), name: 'Beans'},
            {id: uuid(), name: 'Black Pudding'}
        ]
    }

    render(){
        const {items} = this.state;

        return(
            <button
                onClick={() =>{
                    const name = prompt('Enter Item');
                    if(name){
                        this.setState(state => ({
                            items: [...state.items, {id: uuid(), name}]
                        }));
                    }
                }}
            >
                Add Item
            </button>
            <ul>
                {items.map(({id,name}) => (
                    <li key={id}>
                        {name}
                    </li>
                ))}
            </ul>
        )
    }
}

export default ShoppingList

标签: reactjs

解决方案


你只需要一个顶级 JSX 元素。请参阅我添加的额外 div。

编辑 我想指出@cr05s19xx 关于提取 onClick 处理程序的答案。使用这种逻辑是一种很好的行为。此外,如果额外div破坏了一些 CSS,那么您可以React.Fragment按照 @cr05s19xx 的建议再次使用。所以,另一个答案可能比我的更好:)

class ShoppingList extends React.Component {
  state = {
    items: [
      { id: 1, name: "Eggs" },
      { id: 2, name: "Bacon" },
      { id: 3, name: "Beans" },
      { id: 4, name: "Black Pudding" }
    ]
  };

  render() {
    const { items } = this.state;

    return (
      <div>
        <button
          onClick={() => {
            const name = prompt("Enter Item");
            if (name) {
              this.setState(state => ({
                items: [...state.items, { id: uuid(), name }]
              }));
            }
          }}
        >
          Add Item
        </button>
        <ul>
          {items.map(({ id, name }) => (
            <li key={id}>{name}</li>
          ))}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(
  <ShoppingList />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />


推荐阅读