将具有状态的类组件转换为带有钩子的功能组件

时间:2020-10-26 11:52:31

标签: reactjs react-hooks react-functional-component

我很难将类组件转换为函数。我已经看过多个执行此任务的示例,但我仍然了解基础知识。如何使用useState和useEffect挂钩将代码更改为功能组件,并且如果有人有一些资源可以在该主题上找到最佳实践,如何将其更改为功能组件?这是我要转换的代码示例:

Response:
{
  "errorMessage": "Object of type Binary is not JSON serializable",
  "errorType": "TypeError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 14, in lambda_handler\n    print(json.dumps(response))\n",
    "  File \"/var/lang/lib/python3.7/json/__init__.py\", line 231, in dumps\n    return _default_encoder.encode(obj)\n",
    "  File \"/var/lang/lib/python3.7/json/encoder.py\", line 199, in encode\n    chunks = self.iterencode(o, _one_shot=True)\n",
    "  File \"/var/lang/lib/python3.7/json/encoder.py\", line 257, in iterencode\n    return _iterencode(o, 0)\n",
    "  File \"/var/lang/lib/python3.7/json/encoder.py\", line 179, in default\n    raise TypeError(f'Object of type {o.__class__.__name__} '\n"
  ]
}

2 个答案:

答案 0 :(得分:1)

您必须在功能组件中使用useContext才能获得上下文。

const ctx = React.createContext();

function ProductProvider(props) {
  const [products, setProducts] = React.useState([]);
  const [detailProduct, setDetailProduct] = React.useState(detailProduct);
  const ProductContext = React.useContext(ctx);

  React.useEffect(() => {
    handleProducts();
  }, []);

  function handleProducts() {
    let tempProducts = [];
    storeProducts.forEach(item => {
      const singleItem = { ...item };
      tempProducts = [...tempProducts, singleItem];
    });

    setProducts(tempProducts);

    // it could simple be written as
    setProducts(storeProducts);
  }

  function handleDetail() {
    console.log("hello from detail");
  }

  function addToCart() {
    console.log("hello from addToCart");
  }

  return (
    <ProductContext.Provider
      value={{
        products,
        detailProduct,
        handleDetail,
        addToCart
      }}
    >
      {props.children}
    </ProductContext.Provider>
  );
}

答案 1 :(得分:0)

我尝试了@Prateek Thapa代码,但它向我显示了未定义ProviderContext的错误。之所以显示该错误,是因为在我的函数之后我有了一个常量:
const ProductCounsumer = ProductContext.Consumer
不在函数中。
我也将data.js中的const名称更改为'detailedProduct',因为它与useEffect行中的const具有相同的名称。因此,在进行了这些更改之后,我得到了没有错误的示例,但是仍然不确定是否可以正常工作。如果我有这个,可以在没有useContext的情况下工作:

import React, { useState, useEffect } from "react";
import { storeProducts, detailedProduct } from "./data";

const ProductContext = React.createContext();
//Provider
//Consumer

function ProductProvider(props) {
    const [products, setProducts] = useState([]);
    const [detailProduct, setDetailProduct] = useState(detailedProduct);

    useEffect(() => {
      handleProducts();
    }, []);

    function handleProducts() {
      let tempProducts = [];
      storeProducts.forEach(item => {
        const singleItem = { ...item };
        tempProducts = [...tempProducts, singleItem];
      });

      setProducts(tempProducts);

      setProducts(storeProducts);
    }

    function handleDetail() {
      console.log("hello from detail");
    }

    function addToCart() {
      console.log("hello from addToCart");
    }

    return (
      <ProductContext.Provider
        value={{
          products,
          detailProduct,
          handleDetail,
          addToCart
        }}
      >
        {props.children}
      </ProductContext.Provider>
    );
  }
const ProductConsumer = ProductContext.Consumer;

export { ProductProvider, ProductConsumer };