javascript - 使用 React Hooks 设置嵌套数组的状态

标签 javascript reactjs typescript react-hooks

我使用 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>
);
}

最佳答案

您需要使用团队索引并使用 spread syntax 更新特定团队的值和 slice喜欢

  function addPlayer(index) {
    setTeams(prevTeams => {
      return [ ...prevTeams.slice(0, index), {...prevTeams[index], players: [...prevTeams[index].players, "c"] }, ...prevTeams.slice(index+1)];
    });
  }

或者更好的是你可以只使用 map 来更新

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;

function Team() {
  const [teams, setTeams] = useState([{ id: "1", players: ["a", "b"] }]);

  function addPlayer(index) {
    setTeams(prevTeams => {
      return [ ...prevTeams.slice(0, index), {...prevTeams[index], players: [...prevTeams[index].players, "c"] }, ...prevTeams.slice(index+1)];
    });
  }

  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={() => addPlayer(teamIndex)}>Add player</button>
          </div>
        );
      })}
    </div>
  );
}

ReactDOM.render(<Team />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

关于javascript - 使用 React Hooks 设置嵌套数组的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55225764/

相关文章:

javascript - react native Flexbox : Distributing the items evenly

javascript - redux.js 中的 fetch(url) 使用错误的端口

javascript - 类型错误 : state is not iterable

javascript - 在 Typescript 应用程序中使用 Windows 运行时组件

asynchronous - 在具有异步数据调用的小部件内绑定(bind) "foreach"

typescript - ESLint - TypeScript 类型/接口(interface)中的函数参数上的 "no-unused-vars"

javascript - 在 Javascript/Jquery 中按住一个按键(Shift 键)

javascript - 高速全屏 JS 面部检测

javascript - 如何从对象数组中渲染所有对象属性

javascript - react : TypeError: Cannot read property 'Item' of undefined