无效的挂接调用。挂钩只能在功能组件的主体内部调用。

时间:2019-09-24 21:11:49

标签: javascript reactjs

我正在努力解决这个问题。我想用useEffect()替换componentDidMount(),但出现错误。

const requestData = group => {
  useEffect(() => {
    fetch("http://localhost:4996/getTagsFromWebsite", {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=utf-8",
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify(group),
    })
      .then(response => {
        return response.json();
      })
      .then(data => {
        console.log("request data", data);
        // debugger;
        setTagsData(data);
      });

  }, []);
};

1 个答案:

答案 0 :(得分:1)

您可以直接在组件内部调用useEffect()并像这样设置requestData

function App(){
const [requestData, setRequestData] = useState(null);
  useEffect(() => {
    fetch("http://localhost:4996/getTagsFromWebsite", {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=utf-8",
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify(group),
    })
      .then(response => {
        return setRequestData(response.json());
      })
      .then(data => {
        console.log("request data", data);
        // debugger;
        setTagsData(data);
      });

  }, []);
}

如果您希望这是一个钩子,请这样称呼它:

function useRequestData(route){
  const [requestData, setRequestData] = useState(null);
  const [tagsData, setTagsData] = useState(null);
  useEffect(() => {
    fetch(route, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=utf-8",
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify(group),
    })
      .then(response => {
        return setRequestData(response.json());
      })
      .then(data => {
        console.log("request data", data);
        // debugger;
        setTagsData(data);
      });
  }, []);
  // return [loading, data]
  return [!requestData, requestData, tagsData];
}

function App(){
  const [loading, data, err] =  
  useRequestData("http://localhost:4996/getTagsFromWebsite");
  return loading ? "loading..." : data.foobar;
}

希望这会有所帮助,