Analysis: Why does an empty element appear at the first index position every time?
P粉878510551
P粉878510551 2023-08-16 21:12:28
0
1
331

Whenever I try to put something into my to-do list, there is always an empty element at the first index. Why does this happen?

const [todoList, setTodoList] = useState([]); const addToList = (inputText) => { if (inputText === "") { alert("The list is empty") }else{ setTodoList([inputText, ...todoList]) } console.log(todoList); }; const addList = (inputText) => { addToList(inputText); };
const [todoList, setTodoList] = useState([]); const addToList = (inputText) => { if (inputText === "") { alert("The list is empty") }else{ setTodoList([...todoList, inputText]) } console.log(todoList); }; const addList = (inputText) => { addToList(inputText); };

I also tried it but it didn’t work

P粉878510551
P粉878510551

reply all (1)
P粉391955763

Your

setTodoList([inputText, ...todoList])

Use a closure to get thetodoList, so you get the sametodoListevery time.

You need to do something like this:

setTodoList(todoList => [inputText, ...todoList])
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!