我目前正在嘗試使用 React 建立一個 Web 應用程序,提示使用者使用表單輸入一些內容。提交時,程式碼會建立一個物件“teammate”,然後推送到陣列“Team”。然後,我希望使用地圖方法循環遍歷我的數組,並將所有隊友物件顯示在每張卡片上。我不明白為什麼 App.js 的第 94 行沒有顯示我的陣列。請幫助任何建議,我們將不勝感激。
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;
在偵錯中,我發現我的運行到達了 App.js 中的第 94 行,但從未開始 Team.map 迭代。
Your Answer
1 個答案
問題出在你更新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迭代將顯示更新後的陣列元素。
Hot Questions
function_exists()無法判定自訂函數
2024-04-29 11:01:01
google 瀏覽器 手機版顯示的怎麼實現
2024-04-23 00:22:19
子窗口操作父窗口,輸出沒反應
2024-04-19 15:37:47
父視窗沒有輸出
2024-04-18 23:52:34
關於CSS心智圖的課件在哪?
2024-04-16 10:10:18
Hot Tools
vc9-vc14(32+64位元)運行庫合集(連結在下方)
phpStudy安裝所需運行函式庫集合下載
VC9 32位
VC9 32位元 phpstudy整合安裝環境運行庫
php程式設計師工具箱完整版
程式設計師工具箱 v1.0 php整合環境
VC11 32位
VC11 32位元 phpstudy整合安裝環境運行庫
SublimeText3漢化版
中文版,非常好用
熱門話題
抖音等級價目表1-75
20335
7
20335
7
wifi顯示無ip分配
13531
4
13531
4
虛擬手機號碼接收驗證碼
11850
4
11850
4
gmail信箱登陸入口在哪裡
8835
17
8835
17
windows安全中心怎麼關閉
8420
7
8420
7
熱門文章
2025年加密貨幣市場十大趨勢預測:下一個風口在哪裡?
2025-11-07
By DDD
Galaxy的觀點:山寨幣ETF大軍即將到來 哪些的前景會光明
2025-11-08
By DDD
鐵路12306支付失敗訂單還在嗎_鐵路12306支付失敗訂單處理方法
2025-11-07
By DDD
win10字體安裝後在軟件裡找不到怎麼辦_win10字體安裝與識別方法
2025-11-07
By DDD
解決CSS @media 查詢優先級與規則覆蓋問題的教程
2025-11-07
By DDD





