即使在说明我的依赖性之后,React使用效应仍会继续提取

发布于 2025-01-25 18:18:57 字数 1198 浏览 4 评论 0原文

即使在提交任务后,我的使用效率依赖重新订阅后,我的JSON服务器上的使用效应也无限地获取。它确实重新渲染了,但是在我的控制台中,我看到它不断提出请求。我的代码似乎缺少的东西。谢谢

function TodoListComponent() {

const [todos, setTodos] = useState([])
const [nameOfTask, setnameOfTask] = useState('')

const url = `http://localhost:3002/todos`

const addTodo = () => {

const task = {nameOfTask}

  fetch('http://localhost:3002/todos', {
    method: 'POST',
    headers: {"Content-type" : "application/json"},
    body: JSON.stringify(task)
  })
  setnameOfTask('')
}
useEffect(() => {
  fetch(url).then(res => res.json()).then(data => setTodos(data))
}, [todos])


return (
<div>
  <div className='head-container'>
    <div className="input-container">
      <input type="text" value={nameOfTask} onChange={(e) => setnameOfTask(e.target.value)}/>
      <button onClick={() => {
        addTodo()
      }}>add</button>
    </div>
  </div>
  <div className="todo-container">
        {todos.map(todo => (
            <div key={todo.id} className="todo-list">
                <p>{todo.nameOfTask}</p>
            </div>
        ))}
  </div>
</div>
)

I'm having infinite fetch on my json-server with my useEffect even after I put my dependency for re-rendering after submitting task. It does re-render but in my console I see that it keeps fetching get request. What seems to be lacking on my code. Thank you

function TodoListComponent() {

const [todos, setTodos] = useState([])
const [nameOfTask, setnameOfTask] = useState('')

const url = `http://localhost:3002/todos`

const addTodo = () => {

const task = {nameOfTask}

  fetch('http://localhost:3002/todos', {
    method: 'POST',
    headers: {"Content-type" : "application/json"},
    body: JSON.stringify(task)
  })
  setnameOfTask('')
}
useEffect(() => {
  fetch(url).then(res => res.json()).then(data => setTodos(data))
}, [todos])


return (
<div>
  <div className='head-container'>
    <div className="input-container">
      <input type="text" value={nameOfTask} onChange={(e) => setnameOfTask(e.target.value)}/>
      <button onClick={() => {
        addTodo()
      }}>add</button>
    </div>
  </div>
  <div className="todo-container">
        {todos.map(todo => (
            <div key={todo.id} className="todo-list">
                <p>{todo.nameOfTask}</p>
            </div>
        ))}
  </div>
</div>
)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文