【发布时间】:2019-03-18 16:19:08
【问题描述】:
我使用 React Hooks 已经有一段时间了,但对我来说最大的问题是使用数组。
我正在为团队制作注册表。球队有球员(字符串数组)。
用户应该能够添加一个团队,并且对于每个团队,都会显示一个输入,并在输入上方显示团队中的当前成员。
我的问题:如何使用 React Hooks 设置嵌套数组的状态?
在按钮点击时,它应该(现在)将一个字符串添加到当前球队的球员数组中。
我的代码:
interface ITeam {
id: string;
players: Array<string>;
}
export default function Team() {
const [teams, setTeams] = useState<Array<ITeam>>([{id: '1', players: ['a', 'b']}]);
return (
<div>
{teams.map((team, teamIndex) => {
return (
<div key={teamIndex}>
<h2>Team {teamIndex + 1}</h2>
<ul>
{team.players.map((player, playerIndex) => {
return (
<div key={playerIndex}>
{player}
</div>
);
})}
</ul>
<button onClick={() => setTeams([...teams, team.players.concat('c')])}>Add player</button>
</div>
);
})}
</div>
);
}
【问题讨论】:
标签: javascript reactjs typescript react-hooks