【发布时间】:2021-02-01 09:14:00
【问题描述】:
我试图在每次单击按钮时将新对象值推送到数组中。取而代之的是,它替换了以前的值。我认为这个问题与参考有关,但似乎无法解决。
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)
})
}
【问题讨论】:
-
你怎么知道它替换了之前的值?你为什么不安慰
transList?另外请发布更多代码。 -
@Michael 我已经控制了“transList”,请查看 clickHandler 函数。这也是大部分代码,其余的是 HTML 部分/ React DOM 部分。
-
您好,请问您可以添加使用控制台获得的结果吗?你期望什么?只是为了确定
-
@MathKimRobin 嗨,请看一下 Nadia 的回答,我也在寻找同样的答案。
标签: javascript arrays reactjs react-hooks