我试图使用useState挂钩增加ID值,但它没有递增.我必须调用FCT两次才能使id递增.我可以通过控制台记录usEstate之前和之后的对象,但我发现结果相同
function ToDoListApp() {
const [noteList, setNoteList]=useState([])
const [note,setNote]=useState({ noteId: 0 , txt: "", noteState: false })
function addToList(e) {
e.preventDefault();
if(noteList.length===0){
console.log(note)
setNote({noteId: 0 , txt: note.txt ,noteState: false })
setNoteList(noteList=>[...noteList,note])
}else{
console.log(note)
console.log(noteList[noteList.length-1].noteId + 1)
setNote({noteId:noteList[noteList.length-1].noteId + 1,txt:note.txt, noteState:false})
setNoteList(noteList=>[...noteList,note])
console.log(note)
}
}
function deleteItemFromList(e,id){
setNoteList(noteList.filter(note => note.noteId !== id ))
console.log(noteList.length)
}
function handleTheNoteTxt(e) {
e.preventDefault();
setNote({
...note,
txt:e.target.value
})
}
const notesDiplay =noteList.map((note)=>
<Stack key={note.noteId} direction="row" className="note-styling" justifyContent="center" alignItems="center" spacing={2}>
<p>{note.txt} </p>
<p>{note.noteId} </p>
<Button onClick={e => deleteItemFromList(e,note.noteId)} variant="outlined" size='small' >X</Button>
</Stack>
)
return (
<div>
<Stack direction="column" justifyContent="center" alignItems="center">
<Stack className='note-app-container bg1' direction="column" justifyContent="flex-start" alignItems="center" spacing={2} >
<div className='notes-input bg3'>
<TextField autoFocus label="Add your note" variant="standard" value={note.txt}
onChange={handleTheNoteTxt}/>
<Button variant="outlined" size='medium' onClick={addToList}>Add</Button>
</div>
<div className='notes-container bg3'>
{notesDiplay}
</div>
</Stack>
</Stack>
</div>
)
}
export default ToDoListApp`