javascript React,组件调用多次我的后端

owfi6suc  于 2023-04-10  发布在  Java
关注(0)|答案(3)|浏览(135)

我对React相对较新,正在学习它。我试图使用axios获得一个新的帖子。但是当我点击'/getPost' URL时,GetPost组件正在不断调用后端。这是预期的行为吗?
下面是代码片段:

// important imports
import React from 'react'
import { BrowserRouter as Router,Route, Routes }
    from 'react-router-dom';
import './App.css';
import Create from './component/Create';
import Edit from './component/Edit';
import GetPost from './component/GetPost';
import Home from './component/Home';

function App ()  {
  return (
  <div className='App'>
    <Router>
      <Routes>
        <Route path ='' element= {<Home></Home>}> </Route>
        <Route path ='/edit' aelement= {<Edit/>}> </Route>
        <Route path='/create' element= {<Create/>}></Route>
        <Route path='/getPost' element= {<GetPost/>}></Route>
      </Routes>
    </Router>

  </div>

  )
}

export default App;
import React, { useState } from 'react';
import axios from 'axios';
const GetPost = () => {
    const [person, setPerson] = useState([]);

    axios.get(`https://jsonplaceholder.typicode.com/users`)
        .then(res => {

            console.log(res.data);
            setPerson(res.data);
        })

    return (
        person.map(p =>
            <div>
                {p.id}
            </div>
        )
    )

}
export default GetPost;
kcwpcxri

kcwpcxri1#

这是因为axiosGetPost内部调用。它在组件挂载时执行,并通过调用setPerson(res.data)设置状态,这将触发重新渲染,然后axios部分被重新执行,这将是永远的。
为了避免这个问题,你需要使用React中的useEffect钩子,比如:

import React, { useState, useEffect } from "react";
import axios from "axios";
const GetPost = () => {
  const [person, setPerson] = useState([]);

  useEffect(() => {
    axios.get(`https://jsonplaceholder.typicode.com/users`).then((res) => {
      console.log(res.data);
      setPerson(res.data);
    });
  }, []);

  return person.map((p) => <div>{p.id}</div>);
};
export default GetPost;
iugsix8n

iugsix8n2#

如何在useEffect中获取数据,如下所示?

useEffect(() => {
   const load = async () => {
     const res = await axios.get(`https://jsonplaceholder.typicode.com/users`)
     console.log(res.data);
     setPerson(res.data);
   }

   load();
}, []);

我猜GetPost组件不断被调用的原因是您更新了组件中的状态,这导致重新呈现组件,如这里所解释的。

zaq34kh6

zaq34kh63#

在UseEffect中调用API来解决此问题-

useEffect(()=>{
      axios.get(`https://jsonplaceholder.typicode.com/users`)
        .then(res => {
            console.log(res.data);
            setPerson(res.data);
      })
},[])

另外,你在你的App.js中做了如下的修改:

<div className='App'>
<Router>
  <Routes>
    <Route exact path ='/' element= {<Home/>}> </Route>
    <Route exact path ='/edit' element= {<Edit/>}> </Route>
    <Route exact path='/create' element= {<Create/>}></Route>
    <Route exact path='/getPost' element= {<GetPost/>}></Route>
  </Routes>
</Router>

相关问题