【发布时间】:2020-10-12 16:55:17
【问题描述】:
import React, { useState } from 'react';
import './StockQuotes.css';
import { createMuiTheme, withStyles, makeStyles, ThemeProvider } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import stockData from '../util/stockData';
import { useDispatch } from 'react-redux';
import { getStocksOwned } from '../slices/stocksOwnedSlice';
const StockQuotes = () => {
const [sharesToBuy, setSharesToBuy] = useState(stockData);
const dispatch = useDispatch();
const handleChange = (event, index) => {
stockData[index].owned = parseInt(event.target.value);
setSharesToBuy(stockData);
}
const handleClick = (event, index) => {
event.preventDefault();
dispatch(getStocksOwned(sharesToBuy));
stockData[index].owned = 0;
}
const StyledTableCell = withStyles((theme) => ({
head: {
backgroundColor: theme.palette.common.black,
color: theme.palette.common.white,
},
body: {
fontSize: 14,
},
}))(TableCell);
const StyledTableRow = withStyles((theme) => ({
root: {
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
},
}))(TableRow);
const useStyles = makeStyles((theme) => ({
margin: {
margin: theme.spacing(1),
},
table: {
minWidth: 700,
},
}));
const classes = useStyles();
const theme = createMuiTheme({
palette: {
primary: {main: '#00e676'},
},
});
return(
<TableContainer component={Paper}>
<Table className={classes.table} aria-label="customized table">
<TableHead>
<TableRow>
<StyledTableCell>Stock Name</StyledTableCell>
<StyledTableCell align="right">Current Price</StyledTableCell>
<StyledTableCell align="right">Shares</StyledTableCell>
<StyledTableCell align="right">Order</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{stockData.map((stock, index) => (
<StyledTableRow key = {index} >
<StyledTableCell component="th" scope="row">
{stock.name}
</StyledTableCell>
<StyledTableCell align="right">${stock.price}</StyledTableCell>
<StyledTableCell align="right"><input type="number" onChange={event => handleChange(event, index)}></input></StyledTableCell>
<StyledTableCell align="right">
<ThemeProvider theme={theme}>
<Button variant="contained" color="primary" className={classes.margin} onClick={event => handleClick(event, index)}>
BUY
</Button>
</ThemeProvider>
</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
)
}
export default StockQuotes;
单击提交按钮后,我试图将 stockData[index].owned 设置为 0。通常是直截了当的,但这次通过映射包含 8 个对象的 stockData json 文件创建了 8 个输入字段。因此,如果我通过输入标签放置 value 属性然后键入,整个 8 个输入字段都会更改。所以我以这种方式编码,除非在单击后,我得到“TypeError:无法分配给对象'#'的只读属性'拥有'”。我能做什么?
【问题讨论】:
标签: javascript reactjs redux react-redux