【问题标题】:I want to convert React Class to Function (React Hooks)我想将 React 类转换为函数(React Hooks)
【发布时间】:2021-09-17 06:01:47
【问题描述】:

我是 React 初学者。我试图将使用类编写的 React 代码转换为函数或 React Hooks。这是我的代码

import React, { Component, useState } from "react";
import { Badge, Card, Col, ListGroup, Row } from "react-bootstrap";
import { numberWithCommas } from "../utils/utils";
import Keranjang from "./Keranjang";
import TotalBayar from "./TotalBayar";
import { API_URL } from "../utils/constants";
import axios from "axios";
import swal from "sweetalert";

export default function Hasil(props) {

  const [showModal, setShowModal] = useState(false);
  const [keranjangDetail, setKeranjangDetail] = useState(false);
  const [jumlah, setJumlah] = useState(0);
  const [keterangan, setKeterangan] = useState("");
  const [totalHarga, setTotalHarga] = useState(0);

  const handleShow = (menuKeranjang) => {
    setShowModal(true);
    setKeranjangDetail(menuKeranjang);
    setJumlah(menuKeranjang.jumlah);
    setKeterangan(menuKeranjang.keterangan);
    setTotalHarga(menuKeranjang.total_harga);
  };

  const handleClose = () => {
    setShowModal(false);
  };

  const tambah = () => {
    setJumlah(jumlah + 1);
    setTotalHarga(keranjangDetail.product.harga * (jumlah + 1));
  };

  const kurang = () => {
    if (jumlah !== 1) {
      setJumlah(jumlah - 1),
        setTotalHarga(keranjangDetail.product.harga * (jumlah - 1));
    }
  };

  const changeHandler = (event) => {
    setKeterangan(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();

    handleClose();

    const data = {
      jumlah: jumlah,
      total_harga: totalHarga,
      product: keranjangDetail.product,
      keterangan: keterangan,
    };

    axios
      .put(API_URL + "keranjangs/" + keranjangDetail.id, data)
      .then((res) => {
        swal({
          title: "Update Pesanan!",
          text: "Sukses Update Pesanan " + data.product.nama,
          icon: "success",
          button: false,
          timer: 1500,
        });
      })
      .catch((error) => {
        console.log("Error yaa ", error);
      });
  };

  const hapusPesanan = (id) => {
    handleClose();

    axios
      .delete(API_URL + "keranjangs/" + id)
      .then((res) => {
        swal({
          title: "Hapus Pesanan!",
          text: "Sukses Hapus Pesanan " + keranjangDetail.product.nama,
          icon: "error",
          button: false,
          timer: 1500,
        });
      })
      .catch((error) => {
        console.log("Error yaa ", error);
      });
  };

  const { keranjangs } = useState(props);
  return (
    <Col md={3} className="mt-3">
      <h4>
        <strong>Keranjang</strong>
      </h4>
      <hr />
      {keranjangs.length !== 0 && (
        <Card className="overflow-auto hasil ">
          <ListGroup variant="flush">
            <Row className="category-aktif">
              <Col xs={2} className="ml-3 mt-2">
                <h5 className="ml-2">Jml</h5>
              </Col>
              <Col>
                <h5 className="mt-2">Produk</h5>
              </Col>
              <Col>
                <strong className="float-right mr-3 mt-2">Total Harga</strong>
              </Col>
            </Row>
            {keranjangs.map((menuKeranjang) => (
              <ListGroup.Item
                key={menuKeranjang.id}
                onClick={() => handleShow(menuKeranjang)}
              >
                <Row>
                  <Col xs={2}>
                    <h4>
                      <Badge pill variant="primary">
                        {menuKeranjang.jumlah}
                      </Badge>
                    </h4>
                  </Col>
                  <Col>
                    <h5>{menuKeranjang.product.nama}</h5>
                    <p>Rp. {numberWithCommas(menuKeranjang.product.harga)}</p>
                  </Col>
                  <Col>
                    <strong className="float-right">
                      Rp. {numberWithCommas(menuKeranjang.total_harga)}
                    </strong>
                  </Col>
                </Row>
              </ListGroup.Item>
            ))}

            <Keranjang
              handleClose={handleClose}
              {...this.state}
              tambah={tambah}
              kurang={kurang}
              changeHandler={changeHandler}
              handleSubmit={handleSubmit}
              hapusPesanan={hapusPesanan}
            />
          </ListGroup>
        </Card>
      )}

      <TotalBayar keranjangs={keranjangs} {...this.props} />
    </Col>
  );
}

但它给出了错误说 ./src/components/Hasil.js Line 68:7: Expected an assignment or function call and instead see an expression no-unused-expressions

但我不知道该怎么办,有人可以帮助我吗?提前谢谢

顺便说一句,这是我在将其转换为函数https://pastebin.com/0vTJ81kJ之前的原始类代码

【问题讨论】:

  • 你的代码 sn-p 中的第 68 行是什么?
  • 我不知道这条线应该实现什么const { keranjangs } = useState(props);,但我很确定它是错误的。
  • 我的第 68 行是 const data @DrewReese 中的 axios

标签: javascript reactjs react-hooks


【解决方案1】:

我认为实际问题与被指责的问题有几条线。

setJumlah(jumlah - 1) 后面有一个多余的逗号

const kurang = () => {
  if (jumlah !== 1) {
    setJumlah(jumlah - 1), // <-- trailing comma at end of line
      setTotalHarga(keranjangDetail.product.harga * (jumlah - 1));
  }
};

应该是

const kurang = () => {
  if (jumlah !== 1) {
    setJumlah(jumlah - 1);
    setTotalHarga(keranjangDetail.product.harga * (jumlah - 1));
  }
};

【讨论】:

    【解决方案2】:

    this.state 行应该以功能方式删除或替换:

    <Keranjang
                  handleClose={handleClose}
                  **{...this.state}** This is not for functional components
                  tambah={tambah}
                  kurang={kurang}
                  changeHandler={changeHandler}
                  handleSubmit={handleSubmit}
                  hapusPesanan={hapusPesanan}
                />
    在这里昏迷也很奇怪

    const kurang = () => {
        if (jumlah !== 1) {
          setJumlah(jumlah - 1),// why coma
            setTotalHarga(keranjangDetail.product.harga * (jumlah - 1));
        }
      };

    【讨论】:

    • 也可以在渲染返回中调用this.props&lt;TotalBayar keranjangs={keranjangs} {...this.props} /&gt;
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2021-11-24
    • 2022-01-17
    • 2020-01-02
    相关资源
    最近更新 更多