简体   繁体   English

在功能组件内的功能组件中调用 useEffect 会导致此消息:Rendered more hooks than the previous render

[英]Calling useEffect in a functional component within a functional component causes this message: Rendered more hooks than during the previous render

first off - Happy Friday!首先 - 星期五快乐!

I just came on here to see if anyone had any input to an issue that I am seeing in my ReactJs application.我只是来这里看看是否有人对我在 ReactJs 应用程序中看到的问题有任何意见。 So I have a functional component renderViews and in that functional component, there are multiple views to render.所以我有一个功能组件renderViews ,在那个功能组件中,有多个视图要渲染。 Then within the renderViews I have another functional component carDetailsView and I try to make a call to an api when that particular component appears(as a modal).然后在renderViews中我有另一个功能组件carDetailsView并且当该特定组件出现时(作为模态)我尝试调用 api。 requestCarsDetails() should only be called when that component appears so thats why I nested a useEffect hook in the carDetailsView . requestCarsDetails()只应在该组件出现时调用,这就是为什么我在 carDetailsView 中嵌套了一个carDetailsView挂钩。 But that causes an issue:但这会导致一个问题:

Rendered more hooks than during the previous render渲染了比上一次渲染更多的钩子

.Please see code below: .请看下面的代码:

    const renderViews = () = > {
    useEffect(()=> {
     requestCarInfos()
      .then((res) => {
      setCars(cars);
       });
     }, []);

    const carDetailsView = () => {
     useEffect(() => {
       requestCarDetails()
         .then((res) => {
          setDetails(res.details);
           });
      }, []);
       return (<div>carDetailsView</div>)
      }

       return (<div>{determineView()}</div>)
    }

The useEffect that is being used at the top level works fine.在顶层使用的 useEffect 工作正常。 The issue only appeared after I added the second useEffect which is in the carDetailsView.该问题仅在我添加了 carDetailsView 中的第二个 useEffect 后才出现。 Any help or advice is appreciated.任何帮助或建议表示赞赏。 Thanks!谢谢!

Its a rule of hooks.这是钩子的规则。

https://reactjs.org/docs/hooks-rules.html https://reactjs.org/docs/hooks-rules.html

Only Call Hooks at the Top Level仅在顶层调用挂钩

Don't call Hooks inside loops, conditions, or nested functions.不要在循环、条件或嵌套函数中调用 Hooks。 Instead, always use Hooks at the top level of your React function, before any early returns.相反,在任何早期返回之前,始终在 React function 的顶层使用 Hooks。 By following this rule, you ensure that Hooks are called in the same order each time a component renders.通过遵循此规则,您可以确保每次组件渲染时都以相同的顺序调用 Hook。 That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.这就是让 React 在多个 useState 和 useEffect 调用之间正确保留 Hooks 的 state 的原因。

React relies on the order in which Hooks are called. React 依赖于调用 Hooks 的顺序。

As long as the order of the Hook calls is the same between renders, React can associate some local state with each of them.只要 Hook 调用的顺序在渲染之间是相同的,React 就可以将一些本地 state 与它们中的每一个相关联。 if we put a Hook call inside a condition we can skip the Hook during rendering, the order of the Hook calls becomes different:如果我们将一个 Hook 调用放在一个条件中,我们可以在渲染期间跳过 Hook,Hook 调用的顺序就会变得不同:

React wouldn't know what to return for the second useState Hook call. React 不知道要为第二次 useState Hook 调用返回什么。 React expected that the second Hook call in this component corresponds to the persistForm effect, just like during the previous render, but it doesn't anymore. React 期望此组件中的第二个 Hook 调用对应于 persistForm 效果,就像在之前的渲染期间一样,但它不再是了。 From that point, every next Hook call after the one we skipped would also shift by one, leading to bugs.从那时起,在我们跳过的 Hook 调用之后的每个下一个 Hook 调用也会移动一个,从而导致错误。

This is why Hooks must be called on the top level of our components.这就是为什么必须在组件的顶层调用 Hooks 的原因。 If we want to run an effect conditionally, we can put that condition inside our Hook:如果我们想有条件地运行效果,我们可以将该条件放在我们的 Hook 中:

use the lint https://www.npmjs.com/package/eslint-plugin-react-hooks使用 lint https://www.npmjs.com/package/eslint-plugin-react-hooks

this is a caveat of using functional components, on each render everything inside the functional component gets kind of executed.这是使用功能组件的警告,在每次渲染时,功能组件内的所有内容都会被执行。 so react needs to maintain the list of all hooks which have been defined when the component was created.所以 React 需要维护在创建组件时定义的所有钩子的列表。 think of it as an array.把它想象成一个数组。

on each render, useState will return the value for you.在每次渲染时,useState 都会为您返回值。 if you understand this, you will understand what stale state also means.如果你明白这一点,你就会明白 stale state 也意味着什么。 ( stale state can happen, when closures occur within these components ) (当这些组件中发生关闭时,可能会发生陈旧的 state )

Something like that?像那样的东西?

 const CarDetailsView = () => { React.useEffect(() => { console.log("Running CarDetailsView useEffect..."); },[]); return( <div>I amCarDetailsView</div> ); }; const Views = () => { const [showCarDetails,setShowCarDetails] = React.useState(false); const toggleCarDetails = () => setShowCarDetails(;showCarDetails). React.useEffect(() => { console.log("Running Views useEffect..;"), };[]); return( <div> <div>I am Views</div> <button onClick={toggleCarDetails}>Toggle car details</button> {showCarDetails && <CarDetailsView/>} </div> ); }; const App = () => { return(<Views/>); }. ReactDOM,render(<App/>.document;getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script> <div id="root"/>

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

相关问题 向地图组件添加 useMemo 或 useCallbacks 会破坏代码并显示错误“渲染的钩子比上一次渲染时更多” - adding useMemo or useCallbacks to the map component breaks the code with error "Rendered more hooks than during the previous render " 功能组件中useEffect()中的useState() - useState() within useEffect() in a functional component 反应钩子错误:渲染的钩子比上一次渲染时更多 - React hooks error: Rendered more hooks than during the previous render React Hooks 渲染了比上一次渲染更多的钩子 - React Hooks Rendered more hooks than during the previous render 在 apollo useQuery 之后渲染的钩子比上一次渲染时更多 - Rendered more hooks than during the previous render after apollo useQuery 添加 fonts 后,比上一次渲染时渲染的钩子更多 - Rendered more hooks than during the previous render after adding fonts React 中的错误:渲染的钩子比上一次渲染时更多 - Error in React: Rendered more hooks than during the previous render 比之前的渲染 REACT.js 渲染了更多的钩子 - Rendered more hooks than during the previous render REACT.js 未捕获(承诺中)错误:渲染的钩子比上一次渲染期间更多 - Uncaught (in promise) Error: Rendered more hooks than during the previous render 错误:渲染的钩子比上一次渲染时更多 - Error: Rendered more hooks than during the previous render
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM