简体   繁体   English

将对象添加到对象的数组并在 React 中设置状态

[英]Adding an Object to an Object's Array and setting the state in React

I am new at React and I come up with an Idea for learning many things in one shot.我是 React 的新手,我想出了一个可以一次性学习很多东西的想法。 I have this component, Its initial state is an array with an object of baseball Players, I need to add new baseball Player's name through an Input field to the state and then, once a baseball Player is added, a second component appears with input fields to add data.我有这个组件,它的初始状态是一个带有棒球运动员对象的数组,我需要通过输入字段将新棒球运动员的名字添加到状态,然后,一旦添加了棒球运动员,第二个组件就会出现输入字段添加数据。

How can I do that?我怎样才能做到这一点?

export default class BaseballPlayerList extends React.Component {
  constructor() {
    super();
    this.state = {
      baseBallPlayers: [
        {
          name: "Barry Bonds",
          seasons: [
            {
              year: 1994,
              homeRuns: 37,
              hitting: 0.294
            },
            {
              year: 1996,
              homeRuns: 40,
              hitting: 0.294
            }
          ]
        }
      ]
    };
    this.addPlayer = this.addPlayer.bind(this);
  }
  addPlayer(e) {
    e.preventDefault();
    const newPLayer = {
      baseBallPlayers: this.state.baseBallPlayers.name,
      seasons: []
    };
    console.log(newPLayer);
    this.setState(prevState => ({
      baseBallPlayers: [...prevState.baseBallPlayers, newPlayer]
    }));
  }
  render() {
    return (
      <div>
        <div>
          <ul>
            {this.state.baseBallPlayers.map((player, idx) => (
              <li key={idx}>
                <PlayerSeasonInfo player={player} />
              </li>
            ))}
          </ul>
        </div>

        <input value={this.state.baseBallPlayers.name} />
        <button onClick={this.addPlayer}>AddPlayer</button>
      </div>
    );
  }
}
export default class PlayerSeasonInfo extends Component {
  constructor(props) {
    super(props);
    this.player = this.props.player;
  }
  render() {
    return (
      <div>
        {this.player && (
          <div>
            <span>{this.baseBallPlayers.name}</span>
            <span>
              <input placeholder="year" />
              <input placeholder="homeRuns" />
              <input placeholder="hitting" />
              <button>AddInfo</button>
            </span>
          </div>
        )}
      </div>
    );
  }
}

here do you have a working example: https://codesandbox.io/s/nervous-yonath-9u2d6这里有一个工作示例: https : //codesandbox.io/s/nervous-yonath-9u2d6

the problem was where you where storing the new name and how you where updating the whole players state.问题在于您在哪里存储新名称以及您如何更新整个玩家状态。

hope the example helps!希望这个例子有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM