我想呈现列表中的项。当按下按钮时,它会将食物(饮料(添加到名为cart的列表中。我想在按下按钮时在材质ui对话框中呈现此列表。它是空白的。我做错了什么?
import { Button, IconButton, List, ListItem, Typography } from "@material-ui/core"
import Order from './Order'
import Dialog from '@material-ui/core/Dialog';
import CloseIcon from '@material-ui/icons/Close';
import Appbar from '@material-ui/core/Appbar'
import Toolbar from '@material-ui/core/Toolbar'
import DialogActions from '@material-ui/core/DialogActions'
import React, {useState} from 'react'
const Menue = () => {
const cart = []
const [cartOpen, setCartOpen] = useState(false)
function toggleOrder(){
alert(cart)
setCartOpen(! cartOpen)
}
function addToCart(e){
cart.push(e.target.innerText)
console.log(cart)
}
return(
<div>
<Typography variant="h2" component="h2" gutterBottom>
Speisekarte
</Typography>
<Typography>Getränke:</Typography>
<Button name = "milch" onClick = {addToCart}>Milch</Button>
<Button name = "cola" onClick = {addToCart}>Cola</Button>
<Button name = "lassi" onClick = {addToCart}>Lassi</Button>
<Button name = "sprite" onClick = {addToCart}>Sprite</Button>
<Button onClick = {toggleOrder}>Order</Button>
<Dialog fullScreen open = {cartOpen} onClose = {toggleOrder}>
{
cart.map(item => {
return(
<h3>{item}</h3>
);
})
}
</Dialog>
</div>
)
}
export default Menue
这就是您需要做的:
const [cart,setCart]=useState([]);
function addToCart(e){
setCart([...cart,e.target.innerText]);
}
你不能像你试图做的那样在react中操作const变量。这并不是改变cart的值,事实上,在你创建变量const(你这样做的方式(之后,你永远无法操作该变量,无论你一开始给它分配了什么值。
购物车需要成为一个状态。将cart更改为useState((,并相应地更改代码以适应它。
您的购物车需要useState
。
const [cart, setCard] = useState([])
然后更新你的addToCart
函数,如下所示:
function addToCard(e) {
setCart(cart => [...cart, e.target.innerText])
}