//我正在控制台上获得无限的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;
答案 0 :(得分:3)
fetch
函数)都会调用 setState
,这将导致无限循环。将其移至useEffect
,以便在安装组件时将其触发一次。
React.useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(result => result.json())
.then(data => setState(data))
}, []);