axios.get 中的无限调用

Str*_*ker 2 reactjs axios

按照一些教程,我制作了一个待办事项应用程序,现在正在努力将其连接到数据库。但这样做时,在发出axios.get请求时,它会被无限期地调用。

我的代码

import React from "react"
import Header from "./Header"   
import Footer from "./Footer"
import Note from "./Note"
import CreateArea from "./CreateArea"
import axios from "axios"

function App(){
    const [notes, setNotes] = React.useState([]);

    React.useEffect(()=>{
        axios.get('http://localhost:3001/user')
        .then(res=>{
            const entry = res.data;
            setNotes(()=>{
                return [...entry];
            })
        })
        .catch(err =>{
            console.log("Error: "+err);
        })
    })



    function addNote(newNote){
        axios.post('http://localhost:3001/user', newNote)
        .then(res=>{console.log(res.data)})
        .catch(err=>{console.log("Error: "+err)})
        setNotes((prevNotes)=>{
            return [...prevNotes, newNote];
        });
        console.log(newNote);
    }
    function deleteNote(id){
        setNotes(prevNotes =>{
            return prevNotes.filter((noteItem, index)=>{
                console.log(noteItem);
                return index !== id;
            });
        });
    }
    return (
        <div>
            <Header />
            <CreateArea onAdd={addNote} />

            {notes.map((noteItem, index)=>{
                return <Note key={index} id={index} title={noteItem.title} content={noteItem.content} onDelete={deleteNote} />
            })}

            <Footer />
        </div>
    )
}
export default App;
Run Code Online (Sandbox Code Playgroud)

我环顾四周,发现了这个线程Axios.get() ReactJS。在此之后,我添加了useEffect正在进行但仍然无限的调用。

Aru*_*han 6

由于您没有将依赖项数组作为调用的第二个参数传递,因此效果会无限运行useEffect。如果您只想在组件安装时运行效果,请传递一个空数组。

\n

来自文档:

\n
\n

如果您只想运行效果并仅清理一次(在安装和卸载时),则可以传递一个空数组 ( []) 作为第二个参数。这告诉 React 你的效果不依赖于 props 或 state 中的任何值,因此它永远不需要重新运行。这不是 \xe2\x80\x99t 作为特殊情况处理的 \xe2\x80\x94 它直接遵循依赖项数组始终如何工作。

\n
\n
React.useEffect(() => {\n  axios\n    .get(\'http://localhost:3001/user\')\n    .then((res) => {\n      setNotes(res.data)\n    })\n    .catch((err) => {\n      console.log(\'Error: \' + err)\n    })\n}, []) // an empty array of dependencies\n
Run Code Online (Sandbox Code Playgroud)\n

如果您设置eslint-plugin-react-hooks,它会显示一条警告以添加setNotes到依赖项数组,因为效果取决于它。添加它是完全可以的,因为函数的引用在重新渲染时不会改变。

\n
React.useEffect(() => {\n  axios\n    .get(\'http://localhost:3001/user\')\n    .then((res) => {\n      setNotes(res.data)\n    })\n    .catch((err) => {\n      console.log(\'Error: \' + err)\n    })\n}, [setNotes])\n
Run Code Online (Sandbox Code Playgroud)\n
\n

这与问题无关,但您不应该对 API URL 进行硬编码。使用环境变量。如果您使用的是Create React App,则可以添加前缀为REACT_APP_to.env的环境变量,或者如果您有自定义 Webpack 设置,则可以使用dotenv-webpack 。

\n