Reactjs 单击按钮上的删除项
我在每个便笺容器中添加了一个删除按钮。然而,目前它没有任何功能。我想我的删除按钮删除一个带有onClick功能的便笺Reactjs 单击按钮上的删除项,reactjs,button,buttonclick,Reactjs,Button,Buttonclick,我在每个便笺容器中添加了一个删除按钮。然而,目前它没有任何功能。我想我的删除按钮删除一个带有onClick功能的便笺 const notesURL= "https://pregnancy-week-by-week.herokuapp.com/notes" export const Notes = () => { const [existingNote, setExistingNote] = useState([]) const [newNote, s
const notesURL= "https://pregnancy-week-by-week.herokuapp.com/notes"
export const Notes = () => {
const [existingNote, setExistingNote] = useState([])
const [newNote, setNewNote] = useState('')
const dispatch = useDispatch();
const onDelete = id => {
dispatch(user.actions.removeNote(id))
}
// fetch existing notes from the API
const fetchNotes = () => {
fetch(notesURL)
.then(response => response.json())
.then ((notes) => {
setExistingNote(notes)
})
}
useEffect(() => {
fetchNotes();
}, []);
const postNote = (event) => {
event.preventDefault();
fetch(notesURL, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message: newNote})
})
.then (response => response.json())
.then(() => {
fetchNotes();
setNewNote('');
})
}
return (
<>
<Sidebar />
<Navbar />
<h1 className="h1-notes">Pregnancy Week By Week</h1>
<div className="new-note-container">
<form onSubmit= {postNote}>
<label>
<p>What week are you in now? How are you feeling?</p>
<textarea
placeholder="Write a new note..."
rows="3"
onChange={(event) => setNewNote(event.target.value)}
value={newNote}>
</textarea>
</label>
<p className="character-count">
{newNote.length} / 400
</p>
<button className="send-note"
type="submit"
disabled={
newNote.length < 5 || newNote.length > 400 ? true : false}>
<p>Add note</p>
</button>
</form>
</div>
<section className="note-wrapper">
<section className="all-notes-container">
{existingNote.map(newNote => {
return(
<div className="note-container" key={newNote._id}>
<p className="note-text">{newNote.message}</p>
<p className="note-added">Added: {moment(newNote.createdAt).format("MMM Do YYYY")}, {moment(newNote.createdAt).format("h:mm:ss A")}</p>
<button className="delete-button"
type="button" >
<p>delete</p>
</button>
</div>
)
})}
</section>
</section>
</>
)
}
<section className="all-notes-container">
{existingNote.map(newNote => {
return(
<div className="note-container" key={newNote._id}>
<p className="note-text">{newNote.message}</p>
<p className="note-added">Added: {moment(newNote.createdAt).format("MMM Do YYYY")}, {moment(newNote.createdAt).format("h:mm:ss A")}</p>
<button className="delete-button"
// Your event should be looking like this, you need to pass the note id
// in order to delete the note
onClick={e => {e.preventDefault(); deleteNote(newNote.id);}}
type="button" >
<p>delete</p>
</button>
</div>
)
})}
</section>
const notesURL=”https://pregnancy-week-by-week.herokuapp.com/notes"
导出常量注释=()=>{
常量[existingNote,setExistingNote]=useState([])
const[newNote,setNewNote]=useState(“”)
const dispatch=usedpatch();
const onDelete=id=>{
分派(user.actions.removeNote(id))
}
//从API获取现有注释
常量fetchNotes=()=>{
取回(notesURL)
.then(response=>response.json())
。然后((注)=>{
设置现有注释(注释)
})
}
useffect(()=>{
fetchNotes();
}, []);
const postNote=(事件)=>{
event.preventDefault();
取{
方法:“POST”,
标题:{'Content-Type':'application/json'},
正文:JSON.stringify({message:newNote})
})
.then(response=>response.json())
.然后(()=>{
fetchNotes();
setNewNote(“”);
})
}
返回(
每周怀孕
你现在几周?感觉怎么样
setNewNote(event.target.value)}
值={newNote}>
{newNote.length}/400
400?对:错}>
添加注释
{existingNote.map(newNote=>{
报税表(
{newNote.message}
添加:{moment(newNote.createdAt).format(“MMM Do yyy”)},{moment(newNote.createdAt).format(“h:mm:ss A”)}
删除
)
})}
)
}
是的,就像你刚才提到的那样。您可以阻止onClick回调中的默认操作,并且只将ID传递给deleteNote函数
const notesURL= "https://pregnancy-week-by-week.herokuapp.com/notes"
export const Notes = () => {
const [existingNote, setExistingNote] = useState([])
const [newNote, setNewNote] = useState('')
const dispatch = useDispatch();
const onDelete = id => {
dispatch(user.actions.removeNote(id))
}
// fetch existing notes from the API
const fetchNotes = () => {
fetch(notesURL)
.then(response => response.json())
.then ((notes) => {
setExistingNote(notes)
})
}
useEffect(() => {
fetchNotes();
}, []);
const postNote = (event) => {
event.preventDefault();
fetch(notesURL, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message: newNote})
})
.then (response => response.json())
.then(() => {
fetchNotes();
setNewNote('');
})
}
return (
<>
<Sidebar />
<Navbar />
<h1 className="h1-notes">Pregnancy Week By Week</h1>
<div className="new-note-container">
<form onSubmit= {postNote}>
<label>
<p>What week are you in now? How are you feeling?</p>
<textarea
placeholder="Write a new note..."
rows="3"
onChange={(event) => setNewNote(event.target.value)}
value={newNote}>
</textarea>
</label>
<p className="character-count">
{newNote.length} / 400
</p>
<button className="send-note"
type="submit"
disabled={
newNote.length < 5 || newNote.length > 400 ? true : false}>
<p>Add note</p>
</button>
</form>
</div>
<section className="note-wrapper">
<section className="all-notes-container">
{existingNote.map(newNote => {
return(
<div className="note-container" key={newNote._id}>
<p className="note-text">{newNote.message}</p>
<p className="note-added">Added: {moment(newNote.createdAt).format("MMM Do YYYY")}, {moment(newNote.createdAt).format("h:mm:ss A")}</p>
<button className="delete-button"
type="button" >
<p>delete</p>
</button>
</div>
)
})}
</section>
</section>
</>
)
}
<section className="all-notes-container">
{existingNote.map(newNote => {
return(
<div className="note-container" key={newNote._id}>
<p className="note-text">{newNote.message}</p>
<p className="note-added">Added: {moment(newNote.createdAt).format("MMM Do YYYY")}, {moment(newNote.createdAt).format("h:mm:ss A")}</p>
<button className="delete-button"
// Your event should be looking like this, you need to pass the note id
// in order to delete the note
onClick={e => {e.preventDefault(); deleteNote(newNote.id);}}
type="button" >
<p>delete</p>
</button>
</div>
)
})}
</section>
解决了强> 我必须将DELETE添加到后端,并在前端添加一个fetch(以及从reducer导入accessToken) 下面列出了我必须添加/更改的新代码 后端:
app.delete('/notes/:notesId', authenticateUser);
app.delete('/notes/:notesId', async (request, response) => {
try {
await Note.deleteOne({ _id: request.params.notesId });
response.status(200).json({ success: 'Note successfully deleted!' });
} catch (error) {
response.status(500).json({ message: 'Could not delete note' });
};
});
前端
const accessToken = useSelector((store) => store.user.login.accessToken);
const deleteNote = (_id) => {
fetch(`https://pregnancy-week-by-week.herokuapp.com/notes/${_id}`, {
method: 'DELETE',
headers: {'Content-Type': 'application/json', 'Authorization': accessToken},
})
.then((response) => {
if (!response.ok) {
throw new Error('Could not delete note');
}
return response.json();
})
}
<button className="delete-button"
type="button"
onClick={ () => {deleteNote(newNote._id)}}
constAccessToken=useSelector((store)=>store.user.login.accessToken);
常量deleteNote=(\u id)=>{
取回(`https://pregnancy-week-by-week.herokuapp.com/notes/${u id}`{
方法:“删除”,
标题:{'Content-Type':'application/json','Authorization':accessToken},
})
。然后((响应)=>{
如果(!response.ok){
抛出新错误('无法删除注释');
}
返回response.json();
})
}
{deleteNote(newNote._id)}
Delete note应该进入api,就像您的Add note
功能一样。如果您使用的是restful API,它将类似于fetch(
${notesURL}/${id},{method:'DELETE',headers:{'Content-Type':'application/json'}})
。问题是您应该将onClick回调传递给包含上述代码的函数。谢谢,我没有考虑过这种方法(之前没有使用过)。是这样的吗constdeleteNote=(event)=>{event.preventDefault();fetch(deleteURL,{method:'DELETE',headers:{'Content-Type':'application/json'},body:json.stringify({})
不确定接下来要在body:json.stringify({})中放什么?