简体   繁体   English

在 React 中无效使用 useEffect function

[英]Invalid use of useEffect in React function

I'm having an issue with calling useEffect from this function. I haven't been using React that long so I may have some glaring issues but this is taking up too much time.我在从这个 function 调用 useEffect 时遇到问题。我使用 React 的时间不长,所以我可能会遇到一些明显的问题,但这会占用太多时间。

My function is as follows:我的function如下:

import React, { Component } from 'react';
import { useState, useEffect } from "react";

export function Sessions() {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [count, setCount] = useState(null);

    useEffect(() => {
        fetch(`https://localhost:7126/api/`)
            .then((response) => {
                if (!response.ok) {
                    throw new Error(
                        `This is an HTTP error: The status is ${response.status}`
                    );
                }
                return response.json();
            })
            .then((actualData) => {
                setData(actualData);
                setError(null);
                setCount(actualData.length);
            })
            .catch((err) => {
                console.log(err.message);
            });
    }, []);


    return (
        <div className="App">
            <h1>Stream Request: {count} records</h1>
            {loading && <div>A moment please...</div>}
            {error && (
                <div>{`There is a problem fetching the post data - ${error}`}</div>
            )}
            <ul>
                {data &&
                    data.map(({ StreamId, EntryTime }) => (
                        <li key={StreamId}>
                            <h3>{EntryTime}</h3>
                        </li>
                    ))}
            </ul>
        </div>
    );
}

The error i'm receiving is我收到的错误是

Warning: Invalid hook call.警告:无效挂机调用。 Hooks can only be called inside of the body of a function component.钩子只能在 function 组件的内部调用。 This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app这可能由于以下原因之一而发生: 1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 您可能违反了 Hooks 规则 3. 您可能有多个 React 副本同一个应用

#1)I have updated React and React-Dom they were both up to date. #1)我更新了 React 和 React-Dom 它们都是最新的。
#2)? #2)? I don't think I am?我不认为我是?

#3) I have verified this using npm ls react and my output is as follows: #3) 我已经使用 npm ls react 验证了这一点,我的 output 如下:

+-- react-dom@18.2.0
| `-- react@18.2.0 deduped
+-- react-router-dom@6.4.3
| +-- react-router@6.4.3
| | `-- react@18.2.0 deduped
| `-- react@18.2.0 deduped
+-- react@18.2.0
`-- reactstrap@9.1.5
  +-- react-popper@2.3.0
  | `-- react@18.2.0 deduped
  +-- react-transition-group@4.4.5
  | `-- react@18.2.0 deduped
  `-- react@18.2.0 deduped

All seem to be deduped?似乎都被删除了? Please help, none of the other questions have helped my issue such as: Invalid Hook Call but not really请帮忙,其他问题都没有帮助我的问题,例如:无效的挂机呼叫但不是真的

Edit I use Sessions via App.js & AppRoutes.js App.js:编辑我通过 App.js 和 AppRoutes.js App.js 使用会话:

import "./stylesheet.css";
import React, { Component } from 'react';
import { Route, Routes } from 'react-router-dom';
import AppRoutes from './AppRoutes';
import { Layout } from './components/Layout';


export default class App extends Component {
    static displayName = App.name;

    render() {
        return (
            <Layout>
                <Routes>
                    {AppRoutes.map((route, index) => {
                        const { element, ...rest } = route;
                        return <Route key={index} {...rest} element={element} />;
                    })}
                </Routes>
            </Layout>
        );
    }
}

AppRoutes.js: AppRoutes.js:

import { Sessions } from "./components/Sessions";
import { Messages } from "./components/Messages";
import { Home } from "./components/Home";

const AppRoutes = [
  {
    index: true,
    element: <Home />
  },
  {
    path: '/sessions',
    element: <Sessions />
  },
  {
    path: '/messages',
    element: <Messages />
  }
];

export default AppRoutes;

I know this is probably not the solution but maybe it could give you some ideas.我知道这可能不是解决方案,但也许它可以给你一些想法。 As you are not await ing the call properly inside your useEffect() , it could be causing issues for your code and errors that are not that descriptive.由于您没有在useEffect()中正确地await调用,因此它可能会导致您的代码出现问题和不那么具有描述性的错误。

Here are some suggestions:以下是一些建议:

  • use the async / await API instead of the .then() / .catch() from Promises.使用async / await API 而不是 Promises 中的 .then( .then() / .catch()
  • create an internal function for your asynchronous function and call it inside the useEffect() hook after defining it.为您的异步 function 创建一个内部 function 并在定义后在useEffect()挂钩中调用它。 In general (from my experience), async calls at "top-level" useEffect() hook trigger some warnings.通常(根据我的经验),“顶级” useEffect()钩子的async调用会触发一些警告。

As a possible solution, this is the code I suggest you change and start from:作为一种可能的解决方案,这是我建议您更改并从以下代码开始的代码:

useEffect(() => {
  const internalFetch = async () => {
    try {
      const actualData = await fetch(`https://localhost:7126/api/`)
      setData(actualData);
      setError(null);
    } catch (err) {
      console.log(err.message);
    }
  }

  internalFetch();
}, []);

You could use data.length directly instead of creating a state for count .您可以直接使用data.length而不是为count创建 state。

Again: I don't know if this will fix your issue but it could give you another error that could be more descriptive.再次:我不知道这是否会解决您的问题,但它可能会给您带来另一个更具描述性的错误。 And, also as a final suggestion, you could use a lib for fetching data such as react-query , that isolates and cache your data for you.而且,作为最后的建议,您可以使用库来获取数据,例如react-query ,它可以为您隔离和缓存数据。

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

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