Heim > Fragen und Antworten > Hauptteil
Ich versuche gerade, mit React eine Webanwendung zu erstellen, die den Benutzer dazu auffordert, über ein Formular etwas einzugeben. Bei der Übermittlung erstellt der Code ein Objekt „teammate“ und verschiebt es dann an das Array „Team“. Ich möchte dann die Kartenmethode verwenden, um mein Array zu durchlaufen und alle Teamkollegenobjekte auf jeder Karte anzuzeigen. Ich verstehe nicht, warum Zeile 94 von App.js mein Array nicht anzeigt. Bitte helfen Sie uns. Vorschläge werden sehr geschätzt.
import logo from './Nemo.jpg'; import './App.css'; import { useState, useEffect } from 'react'; import './Card.css' const App = () => { const NavBar = () => { return( <> <nav> <div style={{display: 'inline-flex'}}> <a href='index.js'> <img src={logo} width="80" height="80" viewBox="0 0 40 40" fill="none"></img> </a> <h1>Metric Dashboard</h1> </div> </nav> <br></br> </> ) } const MyForm = () =>{ //Define Team array const [Team,setTeam] = useState([]); //Function used for submit const handleSubmit = (event) => { event.preventDefault(); let teammate = { myId: Math.floor(Math.random() * 10000), myUserName: document.getElementById('user').value, mySweepName: document.getElementById('SweepName').value, mySweepDate: document.getElementById('SweepDate').value, mySweepCases: document.getElementById('SweepCases').value, update: function() { this.mySweepDate = document.getElementById('SweepDate').value; this.mySweepCases = document.getElementById('SweepCases').value; this.mySweepName = document.getElementById('SweepName').value; } } console.log(teammate) if(Team.length === 0 ){ //If array is empty console.log("This array is empty") Team.push(teammate) console.log("Array is no longer empty") } //If not empty checks if the user submits with the same sweep name. If same, update and not push to array else if(Team.length !== 0 ){ console.log("This Array is not empty") for(let i = 0; i < Team.length; i++){ if(Team[i].mySweepName === document.getElementById('SweepName') && Team[i].myUserName === document.getElementById('user').value){ console.log("Teammate Updated") document.forms[0].reset() return(Team[i].update()) } } //If not empty and no duplicates, push object to array Team.push(teammate) } console.log(Team) document.forms[0].reset() } return( <> <form> SWEEP <br/> Name: <select id="user"> <option value="default">Select your name</option> <option value="John Doe">John Doe</option> <option value="Plain Jane">Plain Jane</option> <option value="Mike Jones">Mike Jones</option> </select><br/> Name of Sweep: <input type='name'placeholder='Name of Sweep' id="SweepName" /><br/> Date: <input type='date' placeholder='Data' id="SweepDate"/><br/> Cases: <input type="number" min="0" placeholder='# of cases' id="SweepCases"/> <br/> <input className='mySubmit' type="submit" onClick= {handleSubmit}/><br/><br/> </form> <div className='cardContainer'> {Team.map((item) =>( <ul key={item.myId} className='sweepCard'> <li>{item.myUserName}</li> <li>Sweep Name: {item.mySweepName}</li> <li>Sweep Date: {item.mySweepDate}</li> <li>Sweep Cases: {item.mySweepCases}</li> </ul> ))} </div> </> ) } return ( <div className='App'> <div className='NavBar_Component'> <NavBar/> </div> <div className='Display_comps'> <div className='tryAgain'> <MyForm/> </div> </div> </div> ); } export default App;
Beim Debuggen habe ich festgestellt, dass mein Lauf Zeile 94 in App.js erreichte, die Team.map-Iteration jedoch nie gestartet wurde.
P粉6511093972023-09-17 13:28:08
问题出在你更新Team状态数组的方式上。在React中,你不应该直接使用push等方法修改状态变量(在这种情况下是Team),因为它不会触发组件的重新渲染,React也不会识别状态更新。
要解决这个问题,你应该使用useState钩子提供的setTeam函数来正确更新状态数组。setTeam函数会更新状态并触发组件的重新渲染,确保新数据被显示出来。
handleSubmit函数:
const handleSubmit = (event) => { event.preventDefault(); const newTeammate = { myId: Math.floor(Math.random() * 10000), myUserName: document.getElementById('user').value, mySweepName: document.getElementById('SweepName').value, mySweepDate: document.getElementById('SweepDate').value, mySweepCases: document.getElementById('SweepCases').value, }; if (Team.length === 0) { console.log('This array is empty'); setTeam([newTeammate]); // 使用setTeam来更新状态数组 console.log('Array is no longer empty'); } else { console.log('This Array is not empty'); const duplicateIndex = Team.findIndex( (item) => item.mySweepName === newTeammate.mySweepName && item.myUserName === newTeammate.myUserName ); if (duplicateIndex !== -1) { console.log('Teammate Updated'); const updatedTeam = [...Team]; updatedTeam[duplicateIndex] = newTeammate; setTeam(updatedTeam); } else { //如果不为空且没有重复项,将对象推入数组 setTeam((prevTeam) => [...prevTeam, newTeammate]); } } console.log(Team); document.forms[0].reset(); };
通过使用setTeam函数并将更新后的状态作为新数组(或先前状态的修改副本)传递,你确保组件重新渲染时显示正确的数据,Team.map迭代将显示更新后的数组元素。