Javascript 使用钩子对console.log()上的无限状态做出反应为什么?
//我在控制台上得到一个infinty console.log()。有什么帮助吗?为什么Javascript 使用钩子对console.log()上的无限状态做出反应为什么?,javascript,reactjs,Javascript,Reactjs,//我在控制台上得到一个infinty console.log()。有什么帮助吗?为什么 import React, {useState} from "react"; const App = ()=>{ let [state, setState] = useState([]) fetch("https://jsonplaceholder.typicode.com/users") .then(result => re
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;
import React,{useState}来自“React”;
常量应用=()=>{
let[state,setState]=useState([])
取回(“https://jsonplaceholder.typicode.com/users")
.then(result=>result.json())
.然后(数据=>设置状态(数据))
console.log(状态)
返回(
嘿
)
}
导出默认应用程序;
fetch
与每个渲染一起调用(以及setState
函数),这将导致无限循环。将其移动到useffect
,以便在安装组件时触发一次
React.useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(result => result.json())
.then(data => setState(data))
}, []);
每次渲染都会调用
fetch
(以及setState
函数),这将导致无限循环。将其移动到useffect
,以便在安装组件时触发一次
React.useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(result => result.json())
.then(data => setState(data))
}, []);
在触发下一次渲染的每个渲染上调用
fetch
。这就是为什么有一个无限循环。在触发下一个渲染的每个渲染上调用fetch
。这就是为什么你有一个无限循环。