Javascript 如何接收功能组件上express发送的数据? 函数头(props){ const[serverData,setServerData]=useState({}); 取('http://localhost:4001/api') .then(res=>res.json()) 。然后((数据)=>{ 设置服务器数据(数据); 控制台日志(数据); }); 返回( {serverData} ); }
我试图让这个功能性的React组件从ExpressAPI获取数据 我的代码编辑器一直关闭,我认为接收数据部分在循环中 如何使此功能组件只获取一次数据,而不使用componentdidmount或类类型组件Javascript 如何接收功能组件上express发送的数据? 函数头(props){ const[serverData,setServerData]=useState({}); 取('http://localhost:4001/api') .then(res=>res.json()) 。然后((数据)=>{ 设置服务器数据(数据); 控制台日志(数据); }); 返回( {serverData} ); },javascript,node.js,reactjs,express,Javascript,Node.js,Reactjs,Express,我试图让这个功能性的React组件从ExpressAPI获取数据 我的代码编辑器一直关闭,我认为接收数据部分在循环中 如何使此功能组件只获取一次数据,而不使用componentdidmount或类类型组件 我尝试了useCallback,但它对我无效。如果要执行此操作,请使用useEffect挂钩。除非依赖项发生更改(此处未列出依赖项),否则If将发生一次 函数头(props){ const[serverData,setServerData]=useState({}); useffect(()=
我尝试了useCallback,但它对我无效。如果要执行此操作,请使用useEffect挂钩。除非依赖项发生更改(此处未列出依赖项),否则If将发生一次
函数头(props){
const[serverData,setServerData]=useState({});
useffect(()=>{
取('http://localhost:4001/api')
.then(res=>res.json())
。然后((数据)=>{
设置服务器数据(数据);
控制台日志(数据);
});
}, []);
返回(
{serverData}
);
}
@Peppermintc我建议首先将fetch调用分离到另一个函数中,并在useffect
钩子中调用它,因为它使它更具可读性和可重用性。尽管在当前的上下文中是可以的,但在将来,如果您需要添加更多的fetch调用,将很难阅读和理解。如果您将所有的fetch调用都放在useffect中,那么将来的代码就有点担心了。这是一个很好的注释。我同意,为了更好的维护,我会记住这一点。只是为了回答他的问题,但我通常会把这个放在服务/文件夹中
function Header(props) {
const [ serverData, setServerData ] = useState({});
fetch('http://localhost:4001/api')
.then(res => res.json())
.then((data) => {
setServerData(data);
console.log(data);
});
return (
<div>{serverData}</div>
);
}
function Header(props) {
const [ serverData, setServerData ] = useState({});
useEffect(() => {
fetch('http://localhost:4001/api')
.then(res => res.json())
.then((data) => {
setServerData(data);
console.log(data);
});
}, []);
return (
<div>{serverData}</div>
);
}