简体   繁体   English

useEffect 钩子无限循环

[英]useEffect hook infinite loop

I am new to react.我是新来的反应。 here is my problem这是我的问题

import React, { useEffect, useState } from "react";
import { useJwt } from "react-jwt";
import { get_single_user_url } from "../../store/api";
import UrlCard from "../UrlCard/UrlCard";
import "./Urls.css";

function Urls() {
  const [urls, setUrls] = useState([]);
  const { decodedToken } = useJwt(localStorage.token);
  const userId = decodedToken !== null ? decodedToken.userId : "";

  useEffect(() => {
    const hit = async (userId) => {
      get_single_user_url(userId).then((data) => setUrls(data));
      const data = await get_single_user_url(userId);
      setUrls(data);
      console.log(data);
    };
    hit(userId);
  }, []);

  return <div className="urls"></div>;
}

export default Urls;

so this useeffect will call a function所以这个useEffect会调用一个函数

get_single_user_data(userId) get_single_user_data(userId)

and it should return an array of urls from the database.它应该从数据库中返回一个 url 数组。 But it returned this但它返回了这个

{kind: "ObjectId", path: "user", reason: {}, stringValue: """", value: "", proto : Object} {kind: "ObjectId", path: "user", reason: {}, stringValue: """", value: "", proto : Object}

This is the function这是功能

export const get_single_user_url = async (userId) => {
  try {
    const response = await axios({
      method: "post",
      url: "http://192.168.43.62:5000/getUrls",
      data: { user: userId },
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
    });
    console.log(response.data);
    return response.data;
  } catch (error) {
    console.log(error.message);
  }
};

here userId is passed through the body.这里 userId 是通过主体传递的。 Now in the backend when I print the value of req.body , it gives user property with an empty string.现在在后端,当我打印req.body的值时,它为用户属性提供一个空字符串。

{ user: "" } {用户:“”}

I have tried it without using useEffect but then it goes into an infinite loop.我在不使用 useEffect 的情况下尝试过它,但随后它进入了无限循环。

Since you have an empty dependency array on your useEffect , it will only fire once.由于您的useEffect上有一个空的依赖数组,它只会触发一次。 It looks like the userId is an empty string when running.运行时看起来userId是一个空字符串。

You'll want to add some logic in your hit function to only make the request if userId is not empty.您需要在您的hit函数中添加一些逻辑,以便仅在userId不为空时发出请求。 Additionally, to get your effect to run when needed, you should add userId to the dependency array ( [userId] ).此外,为了让您的效果在需要时运行,您应该将userId添加到依赖项数组 ( [userId] )。

If userId isn't needed anywhere other than this function, you might use the token instead, and parse the userId in your hit function.如果userId函数之外的任何地方都不需要userId ,您可以改用令牌,并在您的hit函数中解析userId

const [urls, setUrls] = useState([]);
const { decodedToken } = useJwt(localStorage.token);

useEffect(() => {
  const hit = async (decodedToken) => {
    const userId = decodedToken !== null ? decodedToken.userId : "";
    if (!userId) {
      return;
    }
    
    get_single_user_url(userId).then((data) => setUrls(data));
    const data = await get_single_user_url(userId);
    setUrls(data);
    console.log(data);
  };

  hit(decodedToken);
}, [decodedToken]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM