簡體   English   中英

使用鈎子在 console.log() 上反應無限狀態,這是為什么?

[英]React infinity state on console.log() using hooks why is that?

// 我在控制台上得到一個無窮大的 console.log()。 任何幫助為什么會這樣

import React, {useState} from "react";

const App = ()=>{

    let [state, setState] = useState([])

    fetch("https://jsonplaceholder.typicode.com/users")
    .then(result => result.json())
    .then(data => setState(data))


    console.log(state)

    return(
        <h1>Hey there</h1>
    )
}

export default App;

每次渲染(以及setState函數)都會調用fetch ,這將導致無限循環。 將其移動到useEffect以便在組件安裝時觸發一次。

React.useEffect(() => {
   fetch("https://jsonplaceholder.typicode.com/users")
     .then(result => result.json())
     .then(data => setState(data))
}, []);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM