不能在函数内使用反应钩子

时间:2021-01-20 21:07:39

标签: reactjs react-hooks

我正在尝试在名为 EditForm 的函数中使用 react 钩子 useEffect

它一直告诉我:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. 

但我在名为 EditForm 的函数中使用它。

所以我不确定为什么它认为它不在函数中。

有没有办法让它工作?

这是我的代码:

const EditForm = ({
idVal, titleVal, sectionVal, factoryId, departmentId, countryId, dictionName, showMeVal }) => (

const [pcData, setPcData] = useState([]);

useEffect(() => {
    const fetchData = async () => {
        const result = await axios(
            'api/manufacturingData',
        );
        setPcData(result.data.sort((a, b) => a.name.localeCompare(b.name)));
    };
    fetchData();
}, []);
    <div className="app">

        <Formik
            initialValues={{
                id: idVal,
                title: titleVal
        ....etc />

1 个答案:

答案 0 :(得分:1)

试着把你的代码写成这样:

import React, { useState, useEffect } from "react";
import axios from "axios";

const EditForm = ({
  idVal,
  titleVal,
  sectionVal,
  factoryId,
  departmentId,
  countryId,
  dictionName,
  showMeVal,
}) => {
  
  const [pcData, setPcData] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios("api/manufacturingData");
      setPcData(result.data.sort((a, b) => a.name.localeCompare(b.name)));
    };
    fetchData();
  }, []);
  return <div>Your content</div>;
};

export default EditForm;