我正在开发网球应用程序,但在管理很多状态时遇到问题。我会解释一下:网球锦标赛的第一轮有 128 名这样的球员,每一行都有球员和种子。
Array.from(Array(128)).map((p, 索引) => {
const oddIndex = index * 2 + 1
const evenIndex = index * 2 + 2
const getCurrentSeed = (position) => {
const seed = !objectIsEmpty(games) && games?.rounds[round.round]?.positions[position]?.seed
return seed || ''
}
const getCurrentATPPlayer = (position) => {
const ATPPlayer = !objectIsEmpty(games) && games?.rounds[round.round]?.positions[position]?.atp_player
return ATPPlayer || {}
}
<div className="player">
<ATPPlayerFinderWrapper position={oddIndex} setATPPlayerId={setATPPlayerId} setCurrentPosition={setCurrentPosition} ATPPlayer={getCurrentATPPlayer(oddIndex)} />
</div>
<div className="seed">
<TextField
id={`seed${oddIndex}`}
label="Seed"
variant="standard"
onChange={(e) => setSeed(e.target.value)}
InputProps={{ disableUnderline: true }}
value={getCurrentSeed(oddIndex)}
/>
</div>
});
我的大问题是当我从后面获取行时,我需要每个文本字段的状态,但它不起作用并且可能很多。
您可以做的是,将数组置于某种状态并将其每个值设置为
''
。
const [seeds, setSeeds] = useState(Array(128).fill(''));
const [ATPPlayers, setATPPlayers] = useState(Array(128).fill({}));
然后每当状态改变时设置它的值
const handleSeedChange = (position, value) => {
const newSeeds = [...seeds];
newSeeds[position] = value;
setSeeds(newSeeds);
};
const handleATPPlayerChange = (position, player) => {
const newATPPlayers = [...ATPPlayers];
newATPPlayers[position] = player;
setATPPlayers(newATPPlayers);
};
这是根据您的问题的完整代码。
import React, { useState } from 'react';
const TennisBracket = ({ games, round }) => {
const [seeds, setSeeds] = useState(Array(128).fill(''));
const [ATPPlayers, setATPPlayers] = useState(Array(128).fill({}));
const getCurrentSeed = (position) => seeds[position] || '';
const getCurrentATPPlayer = (position) => ATPPlayers[position] || {};
const handleSeedChange = (position, value) => {
const newSeeds = [...seeds];
newSeeds[position] = value;
setSeeds(newSeeds);
};
const handleATPPlayerChange = (position, player) => {
const newATPPlayers = [...ATPPlayers];
newATPPlayers[position] = player;
setATPPlayers(newATPPlayers);
};
return (
<div>
{Array.from(Array(128)).map((p, index) => {
const oddIndex = index * 2 + 1;
return (
<div key={index}>
<div className="player">
{/* Use your ATPPlayerFinderWrapper or any other component */}
{/* Assuming it has a callback to pass the selected player to the parent */}
<ATPPlayerFinderWrapper
position={oddIndex}
setATPPlayerId={setATPPlayerId}
setCurrentPosition={setCurrentPosition}
ATPPlayer={getCurrentATPPlayer(oddIndex)}
onPlayerChange={(player) => handleATPPlayerChange(oddIndex, player)}
/>
</div>
<div className="seed">
<TextField
id={`seed${oddIndex}`}
label="Seed"
variant="standard"
onChange={(e) => handleSeedChange(oddIndex, e.target.value)}
InputProps={{ disableUnderline: true }}
value={getCurrentSeed(oddIndex)}
/>
</div>
</div>
);
})}
</div>
);
};