在无状态功能组件中传递道具

时间:2020-05-05 01:33:52

标签: javascript html reactjs react-hooks

我有一个父亲,即Productos,一个孩子,名为EditarProductos。我想将producto.id传递给EditarProductos。

这是产品:

import {Button, TableHead, TableRow, TableCell, TableBody, Table} from '@material-ui/core'
import { withStyles, makeStyles } from '@material-ui/core/styles';
import InsertarProductos from './InsertarProductos';
import Grid from '@material-ui/core/Grid';
import EditIcon from '@material-ui/icons/Edit';
import DeleteIcon from '@material-ui/icons/Delete';
import EditarProductos from './EditarProductos';

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.background.default,
    },
  },
}))(TableRow);

function Productos(props) {
    const [productos, setProductos] = useState([]);
    var id='';

    useEffect(() => {


      const getProductos = async () => {
        const res = await fetch("/productos", {
            method: 'GET',
            headers: {'Content-Type': 'application/json'},
        })
        //console.log(res);
        const response = await res.json();
        setProductos(response);
      }
      getProductos();
    })

    function editar(producto){
      console.log("entro 1");
      //console.log(producto.id);
      id = producto.id;
      console.log(id);
      return <EditarProductos productoEdit = {id}/>;
    }

    function eliminar(producto){
      console.log(producto.id);
      id=producto.id;
      deleteProductos();
      window.location.reload();
    }

    const deleteProductos = async () => {
      console.log("entro");
      console.log(id);
      const res = await fetch("/productos", {
          method: 'DELETE',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            id: id
          })
      })
      const response = await res.json();
    }

    const useStyles = makeStyles({
      table: {
        minWidth: 700,
      },
    });
    //console.log(plot);

    const mystlye = {
      minWidth: "50%",
      minHeight: 50
    };

    //
    const classes = useStyles();
    return (
      <div>

      <br />
        <Grid container spacing={3}>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}>
         <InsertarProductos productoInsert="fer"/>
        </Grid>
      </Grid>
      <br />
        <Table className={classes.table}>
          <TableHead>
            <TableRow>
              <StyledTableCell>ID</StyledTableCell>
              <StyledTableCell>Nombre</StyledTableCell>
              <StyledTableCell>Precio de Compra</StyledTableCell>
              <StyledTableCell>Precio de Venta</StyledTableCell>
              <StyledTableCell>Cantidad</StyledTableCell>
              <StyledTableCell>Categoria</StyledTableCell>
              <StyledTableCell>Extras</StyledTableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {productos.map((producto) =>
              <TableRow className="data-row">
                <StyledTableCell>{producto.id}</StyledTableCell>
                <StyledTableCell>{producto.nombre}</StyledTableCell>
                <StyledTableCell>{producto.precio_compra}</StyledTableCell>
                <StyledTableCell>{producto.precio_venta}</StyledTableCell>
                <StyledTableCell>{producto.cantidad}</StyledTableCell>
                <StyledTableCell>{producto.categorias_id}</StyledTableCell>
                <StyledTableCell> 
                <Button variant="outlined" onClick={() => editar(producto)}>
                  <EditIcon />
                </Button>
                <Button variant="outlined" onClick={() => eliminar(producto)} ><DeleteIcon /> </Button>
                </StyledTableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    );
}

export default Productos;

如果我尝试将id传递给按钮,它将开始像循环一样多次打印id。

永远不会到达EditarProductos,并且不会传递ID。有人可以帮我解决我的问题吗?

PD:在EditarProductos中,我试图打印ID:

console.log(props.productoEdit);

1 个答案:

答案 0 :(得分:1)

您不能返回(并渲染)这样的UI元素。您可以宁愿设置要显示的产品的ID。使用is可以有条件地将EditarProductos渲染到UI中。在关闭/关闭对话框时,您可能还希望/需要一种方法来重置此设置。

以下是执行此操作的一种方法:

function Productos(props) {
    const [productos, setProductos] = useState([]);
    const [id, setId] = useState(null); // create state variable

    ...

    function editar(producto){
      console.log("entro 1");
      console.log(producto.id);
      setId(producto.id);
    }

    function onEditarClose() {
      setId(null);
    }

    ...

    return (
      <div>
      {id && 
         // conditionally render in UI the dialog
         <EditarProductos onClose={onEditarClose} productoEdit={id} />
      } 
      <br />
        <Grid container spacing={3}>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}>
         <InsertarProductos productoInsert="fer"/>
        </Grid>
      </Grid>
      <br />
        <Table className={classes.table}>
          <TableHead>
            <TableRow>
              <StyledTableCell>ID</StyledTableCell>
              <StyledTableCell>Nombre</StyledTableCell>
              <StyledTableCell>Precio de Compra</StyledTableCell>
              <StyledTableCell>Precio de Venta</StyledTableCell>
              <StyledTableCell>Cantidad</StyledTableCell>
              <StyledTableCell>Categoria</StyledTableCell>
              <StyledTableCell>Extras</StyledTableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {productos.map((producto) =>
              <TableRow className="data-row">
                <StyledTableCell>{producto.id}</StyledTableCell>
                <StyledTableCell>{producto.nombre}</StyledTableCell>
                <StyledTableCell>{producto.precio_compra}</StyledTableCell>
                <StyledTableCell>{producto.precio_venta}</StyledTableCell>
                <StyledTableCell>{producto.cantidad}</StyledTableCell>
                <StyledTableCell>{producto.categorias_id}</StyledTableCell>
                <StyledTableCell> 
                <Button variant="outlined" onClick={() => editar(producto)}>
                  <EditIcon />
                </Button>
                <Button variant="outlined" onClick={() => eliminar(producto)} ><DeleteIcon /> </Button>
                </StyledTableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    );
}