即使在说明我的依赖性之后,React使用效应仍会继续提取
即使在提交任务后,我的使用效率依赖重新订阅后,我的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论