简体   繁体   中英

Add new element to DOM in React

I'm new to React, I try to create add a new element to DOM when onClick. So I play with the state. Like below:

const [number, setNumber] = useState(1);
const [item, setItem] = useState(() => [{id: number,task: `Task ${number}`}]);

const increaseItem = () => {
    setNumber(number + 1)
    console.log(number)
    setItem([...item, {id: number, task: `Task ${number}`}])
    console.log(item)
}

But I got an issue when I push the array in useState, the first element of the array copied twice. Here the result of the array:

4 //result of the number

/* Result of item */
0: {id: 1, task: "Task 1"}
1: {id: 1, task: "Task 1"}
2: {id: 2, task: "Task 2"}
3: {id: 3, task: "Task 3"}

Could you show me how the correct way to solve this. Thank you.

const [number, setNumber] = useState(1);
const [item, setItem] = useState([{
    id: number,
    task: `Task ${number}`
}]);

const increaseItem = () => {
    const newNumber = number + 1;
    setNumber(newNumber);
    console.log(number)
    setItem([...item, {
        id: newNumber,
        task: "Task " + newNumber
    }]);
    console.log(item)
}

increaseItem();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM