为什么我的 javascript 数组被覆盖了? [关闭]

问题描述 投票:0回答:0

我在单页 ReactJS 应用程序中有几个文本输入,其值传递给父组件。 我的函数应该将两个输入值变成一个对象,然后将其推入数组。

当我的函数在单击按钮时运行时,我的数组似乎被输入中的最新条目所取代。据我了解,push() 应该将新项目添加到数组的末尾,而不是替换项目。

App.js

import './App.css';
import Child from './Child';
import { useState } from "react";

function App() {
  const [currName, setCurrName] = useState("");
  const [currAge, setCurrAge] = useState("");

  function updateName(newName) {
    setCurrName(newName);
  }

  function updateAge(newAge) {
    setCurrAge(newAge);
  }

  let obj;
  let objectArray = [];

  function addToArray() {
    obj = {name: currName, age: currAge};
    objectArray.push(obj);
    for(let i=0;i<objectArray.length;i++){
      console.log(objectArray[i]);
    }
  }

  return (
    <div className="App">
      <Child updateAge={updateAge} updateName={updateName} />
      <button onClick={addToArray}>logger</button>
    </div>
  );
}

export default App;

Child.js

        function Child(props) {
        function handleName(event){
            props.updateName(event.target.value)
        }
        function handleAge(event) {
            props.updateAge(event.target.value)
        }
    
        return(
            <div>
            <input onChange={handleName} id="name-input" type="text"/>
            <input onChange={handleAge} id="age-input" type="number" />
            </div>
        )
    } 
    
    export default Child;

数组和对象都在应用程序启动时初始化。该功能仅通过按下按钮运行,仅此而已,所以我看不到它是如何被覆盖的。

javascript reactjs arrays javascript-objects
© www.soinside.com 2019 - 2024. All rights reserved.