我有一个简单的购物清单组件,用于显示状态下的商品
如何使用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
答案 0 :(得分:1)
如果这是您的输出(除非已将其裁剪),请考虑以下事项:
<React.Fragment>
只能呈现一个Root元素,因此将内容包装在render
中您的输出现在看起来像这样
import React, { Component, Fragment } 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' }
]
};
buttonClicked = () => {
const name = prompt('Enter item');
if (name) {
this.setState(state => ({
items: [...state.items, { id: uuid(), name }]
}));
}
};
render() {
const { items } = this.state;
return (
<Fragment>
<button onClick={this.buttonClicked}>Add Item</button>
<ul>
{items.map(({ id, name }) => (
<li key={id}>{name}</li>
))}
</ul>
</Fragment>
);
}
}
请运行此命令,并让我知道是否可行
答案 1 :(得分:1)
您只需要在其中放置一个顶级JSX元素。请参阅我添加的额外div。
修改
我想指出@ cr05s19xx关于提取onClick处理程序的答案。使用此逻辑是一个好习惯。另外,如果多余的div
破坏了某些CSS,那么您可以按照@ cr05s19xx的建议再次使用React.Fragment
。因此,另一个答案可能是比我的更好的答案:)
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" />