简体   繁体   中英

Array.push() method replacing initial index value instead of appending at end

I'm trying to push new object values in array on every button click. Instead of this, it replaces the previous value. I think this problem is related to reference but can't seem to fix it.

var tranList = []
var newText, newAmount
const [Amount, setAmount] = useState("")
const [Text, setText] = useState("")
function textHandler(event) {
    newText = event.target.value;
    setText(newText)
}
function amountHandler(event){
    newAmount = event.target.value;
    setAmount(newAmount)
}
function clickHandler(){
    console.clear()
    var pair = {}
    pair["text"] = Text
    pair["amount"] = Amount 
    tranList.push(pair)
    // checking if object is pushed or not.
    tranList.map(item => {
        return console.log("Text: ", item.text, " Amount: ", item.amount)
     })
}

The problem is in the way you declare tranList

var tranList = []

Which means a brand new variable is created on each render. It is not that the value is replaced on click, it is being added to an empty array instead. What you need to do is to keep in the state

const [tranList , setTranList ] = useState([])

and add new values like

setTranList(list => [...list, newItem])

PS If you try to log tranList values immideatell after calling setTranList you'll notice it is always one step behind, which is expected behaviour, the updated state will be available in useEffect callback or/and on the next render.

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