【发布时间】:2021-12-16 09:22:40
【问题描述】:
我使用 django rest api 制作了类似项目的基本博客,并在前端做出反应,但 useEffect 导致了无限循环,但我找不到原因。我知道它是 useEffect,因为它在制作这个项目之前发生了几次,但我能够修复它,但现在有点困难。还有一个附带问题,你们对代码有什么看法,任何提示或建议都将不胜感激,谢谢。
import React, { useState, useEffect } from 'react';
import './App.css';
const App = () => {
const [posts, setPosts] = useState([])
const [editing, setEditing] = useState(false)
const [editData, setEditData] = useState([])
const [create, setCreate] = useState({
title: "",
description: "",
completed: false
})
const handleCreate = ((e) => {
const newData = {...create}
newData[e.target.id] = e.target.value
setCreate(newData)
})
const handleEdit = ((post) => {
setCreate({
title: post.title,
description: post.description,
})
{setEditing(true)}
{setEditData(post)}
})
const handleDelete = ((post) => {
fetch(`http://127.0.0.1:8000/api/post-delete/${post.id}`,
{
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
}
})
console.log(post.id)
})
const handleSubmit = ((e) => {
e.preventDefault()
var url = 'http://127.0.0.1:8000/api/post-create/'
if (editing == true) {
url = `http://127.0.0.1:8000/api/post-update/${editData.id}`
}
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(create)
})
.then(setCreate({
title: "",
description: "",
completed: false
}))
})
useEffect(async () => {
const response = await fetch('http://127.0.0.1:8000/api/post-list/')
setPosts(await response.json())
}, [posts])
return (
<div className="container">
<div class="row">
<div class="col-7">
<h1 className="p-3 mb-2 bg-dark text-light">The Posts</h1>
{posts.map((post, index) => {
return(
<div key={index} class="list-group-item list-group-item-dark mb-1">
<ul>
<li>
<h3>{post.title}</h3>
<p>{post.description}</p>
<span class="text-muted">{post.created_at.slice(0, 10)}</span>
</li>
</ul>
<div className="d-grid gap-2 d-md-flex justify-content-md-end">
<button onClick={() => handleEdit(post)} class="btn btn-outline-warning m-2" type="button">Edit</button>
<button onClick={() => handleDelete(post)} class="btn btn-outline-danger m-2" type="button">-</button>
</div>
</div>
)
})}
</div>
<div className="col-5">
<form onSubmit={(e) => handleSubmit(e)} className="mx-2 p-3 rounded border border-2 border-dark">
<h1 className="p-3 rounded bg-dark text-light">Add New Post</h1>
{/* TITLE */}
<div style={{ flex: 6 }}>
<label class="form-label">Title</label>
<input onChange={(e) =>handleCreate(e)} className="form-control" id="title" value={create.title} type="text" placeholder="Add Post" />
</div>
{/* DESCRIPTION */}
<div class="mb-3">
<label class="form-label">Description</label>
<textarea onChange={(e) =>handleCreate(e)} className="form-control" id="description" value={create.description} placeholder="Post Description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-dark m-3">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default App;
【问题讨论】:
-
为什么要让
posts成为useEffect的依赖项?这就是问题所在。你更新它,它会更新posts的状态,然后循环不断地继续。您打算何时发出/api/post-list请求?只是在创建组件时?还是什么时候? -
但是如果我从 useEffect 中删除帖子,当我更新帖子时页面不会重新加载是否有解决方法
-
要成为一个完全合适的系统,您需要解决很多问题。当您进行更新时,API 会返回什么? (提示它应该是更新的整个实体)。您应该做的不是重新获取所有数据,因为随着产品的扩展,这会降低效率。您应该更新状态内的数据以反映更改。含义...如果您在 api 返回成功时删除某些内容,您也会从您的状态中删除该条目。重新获取不是正确的方法,而且您现在可能已经知道,它可能会导致错误
-
我明白,所以你说我不要重新获取所有数据,而是在前端过滤掉已删除的帖子,如果这样的话,更新后的帖子呢。可以举个小例子吗
标签: javascript reactjs django django-rest-framework react-hooks