Javascript 使用React钩子设置嵌套数组的状态

Javascript 使用React钩子设置嵌套数组的状态,javascript,reactjs,typescript,react-hooks,Javascript,Reactjs,Typescript,React Hooks,我使用React钩子已经有一段时间了,但对我来说最大的问题是使用数组 我正在为团队制作一份登记表。球队有球员(字符串数组) 用户应该能够添加一个团队,对于每个团队,都会显示一个输入,其中团队中的当前成员显示在输入上方 我的问题:如何设置带有React钩子的嵌套数组的状态? 在点击按钮时,它应该(现在)向当前团队的玩家数组添加一个字符串 我的代码: interface ITeam { id: string; players: Array<string>; } exp

我使用React钩子已经有一段时间了,但对我来说最大的问题是使用数组

我正在为团队制作一份登记表。球队有球员(字符串数组)

用户应该能够添加一个团队,对于每个团队,都会显示一个输入,其中团队中的当前成员显示在输入上方

我的问题:如何设置带有React钩子的嵌套数组的状态?

在点击按钮时,它应该(现在)向当前团队的玩家数组添加一个字符串

我的代码:

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>
);
}
接口ITeam{ id:字符串; 玩家:阵型; } 导出默认功能团队(){ const[teams,setTeams]=useState([{id:'1',players:['a','b']}]); 返回( {teams.map((team,teamIndex)=>{ 返回( 团队{teamIndex+1}
    {team.players.map((player,playerIndex)=>{ 返回( {player} ); })}
setTeams([…teams,team.players.concat('c'))}>添加玩家 ); })} ); }
您需要使用团队索引,并使用等更新特定团队的价值

或者更好的是,您可以使用地图进行更新

function addPlayer(index) {
  setTeams(prevTeams => {
    return prevTeam.map((team, idx) => {
      if(index === idx) {
        return {...prevTeams[index], players: [...prevTeams[index].players, "c"]}
      } else {
        return team;
      }
    })
  });
}
const{useState}=React;
职能小组(){
const[teams,setTeams]=useState([{id:“1”,players:[“a”,“b”]}]);
函数addPlayer(索引){
塞特姆斯(PrevTeam=>{
返回[…prevTeams.slice(0,索引),{…prevTeams[index],玩家:[…prevTeams[index].玩家,“c”},…prevTeams.slice(索引+1)];
});
}
返回(
{teams.map((team,teamIndex)=>{
返回(
团队{teamIndex+1}
    {team.players.map((player,playerIndex)=>{ 返回{player}; })}
添加玩家(团队索引)}>添加玩家 ); })} ); } render(,document.getElementById(“根”))

function addPlayer(index) {
  setTeams(prevTeams => {
    return prevTeam.map((team, idx) => {
      if(index === idx) {
        return {...prevTeams[index], players: [...prevTeams[index].players, "c"]}
      } else {
        return team;
      }
    })
  });
}