Javascript 当我使用react钩子时,API被一次又一次地调用
我正在使用Javascript 当我使用react钩子时,API被一次又一次地调用,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我正在使用React Hooks从现有API获取数据。这是我的密码 import React, { useState, useEffect } from "react"; export const People = () => { const [people, setPeople] = useState([]); const url = "http://127.0.0.1:5000/people"; async function fetchData() { cons
React Hooks
从现有API获取数据。这是我的密码
import React, { useState, useEffect } from "react";
export const People = () => {
const [people, setPeople] = useState([]);
const url = "http://127.0.0.1:5000/people";
async function fetchData() {
console.log("calling api .. ");
const res = await fetch(url);
res.json().then((res) => setPeople(res));
}
useEffect(() => {
fetchData();
});
return (
<div>
<ul>
{people &&
people.map((person) => <li key={person.id}>{person.name}</li>)}
</ul>
</div>
);
};
const Dashboard = (props) => {
return (
<div>
<People />
</div>
);
};
export default Dashboard;
import React,{useState,useffect}来自“React”;
export const People=()=>{
const[people,setPeople]=useState([]);
常量url=”http://127.0.0.1:5000/people";
异步函数fetchData(){
log(“调用api…”);
const res=等待获取(url);
res.json()。然后((res)=>setPeople(res));
}
useffect(()=>{
fetchData();
});
返回(
{人&&
people.map((person)=>- {person.name}
)}
);
};
const仪表板=(道具)=>{
返回(
);
};
导出默认仪表板;
我遇到的问题是这个API被一次又一次地调用。你能告诉我我做错了什么吗
谢谢目前,使用
useffect(callback)
将执行每个渲染的回调
尝试将useffect
与一起使用
如果要运行一个效果并仅清理一次,可以将空数组([]
)作为第二个参数传递这告诉React,您的效果不依赖于道具或状态的任何值,因此它永远不需要重新运行
- 在
用例中检查我的其他useffect
//应该在外部作用域上,因为URL与组件的逻辑解耦
常量url=”http://127.0.0.1:5000/people";
export const People=()=>{
const[people,setPeople]=useState([]);
useffect(()=>{
//这样,不会在每次渲染时都重新指定fetchData
异步函数fetchData(){
log(“调用api…”);
const res=等待获取(URL);
//一致性,不要混合'then'和'wait'语法
const people=wait res.json();
setPeople(人);
}
fetchData();
}, []);
返回(
{人&&
people.map((person)=>- {person.name}
)}
);
};
谢谢,它可以工作,但它有什么作用?你能再详细一点吗?多亏了一个t..循环的存在,因为每当组件中的状态发生变化时,就会调用useffect
,并且在您引用的改变状态的fetchData()
钩子中,就会调用useffect
。对于空的依赖项数组,它只运行一次,就像componentDidMount
@Gaganuseffect
在第二个参数(作为数组)中的变量值发生变化时会触发一样,所以当有空数组时,它意味着componentDidMount
。谢谢大家。。非常感谢您的帮助。请阅读有关Useffect hook的文档。
useEffect(() => {
fetchData();
}, []);
// Should be on the outer scope as the URL is decoupled from the component's logic
const url = "http://127.0.0.1:5000/people";
export const People = () => {
const [people, setPeople] = useState([]);
useEffect(() => {
// This way fetchData won't re-assigned on every render
async function fetchData() {
console.log("calling api .. ");
const res = await fetch(URL);
// Consitstance, don't mix `then` and `await` syntax
const people = await res.json();
setPeople(people);
}
fetchData();
}, []);
return (
<div>
<ul>
{people &&
people.map((person) => <li key={person.id}>{person.name}</li>)}
</ul>
</div>
);
};