在使用地图时,反应“不能读取未定义的属性”

我正在从teamtreehouse.com制作一个非常基本的React应用程序,而且我经常遇到

“TypeError:无法读取属性”onPlayerScoreChange“未定义的”

即使我正确地绑定我的function(我认为)

'onPlayerScoreChange'Grandparent组件中的一个方法,当用户点击“+”或“ – ”button来改变玩家的分数时,该方法就会执行。

如果有人可以解释什么是错误的,这将是非常有帮助的,因为我认为我在伟大的祖父母的构造函数中设置this.onPlayerScoreChange = this.onPlayerScoreChange.bind(this)

父组件:

 class App extends React.Component { constructor(props) { super(props); this.onPlayerScoreChange = this.onPlayerScoreChange.bind(this) this.state = { initialPlayers: props.initialPlayers, }; } onPlayerScoreChange(delta, index) { this.setState((prevState, props) => { return {initialPlayers: this.prevState.initialPlayers[index].score += delta} }) } render() { return( <div className = "scoreboard"> <Header title = {this.props.title}/> <div className = "players"> {this.state.initialPlayers.map(function(player, index) { return( <Player name = {player.name} score = {player.score} key = {player.id} index = {index} onScoreChange = {this.onPlayerScoreChange} /> ) })} </div> </div> ) }} 

(组件具有标题的默认道具)

子组件:

 class Player extends React.Component { render() { return( <div className = "player"> <div className = "player-name"> {this.props.name} </div> <div className = "player-score"> <Counter score = {this.props.score} onChange = {this.props.onScoreChange} index = {this.props.index}/> </div> </div> ) }} 

孙子成分:

 class Counter extends React.Component { constructor(props) { super(props) this.handleDecrement = this.handleDecrement.bind(this) this.handleIncrement = this.handleIncrement.bind(this) } handleDecrement() { this.props.onChange(-1, this.props.index) } handleIncrement() { this.props.onChange(1, this.props.index) } render() { return( <div className = "counter"> <button className = "counter-action decrement" onClick = {this.handleDecrement}> - </button> <div className = "counter-score"> {this.props.score} </div> <button className = "counter-action increment" onClick = {this.handleIncrement}> + </button> </div> )}} 

谢谢!

您还没有为使用onScoreChange = {this.onPlayerScoreChange}的map函数进行绑定,

您可以使用绑定或箭头函数进行绑定

PS绑定是需要的,因为映射函数的上下文不同于React Component上下文,因此这个函数内部不会引用React Components,因此你不能访问React Component类的属性。

带箭头function:

  {this.state.initialPlayers.map((player, index)=> { return( <Player name = {player.name} score = {player.score} key = {player.id} index = {index} onScoreChange = {this.onPlayerScoreChange} /> ) })} 

用绑定

  {this.state.initialPlayers.map(function(player, index) { return( <Player name = {player.name} score = {player.score} key = {player.id} index = {index} onScoreChange = {this.onPlayerScoreChange} /> ) }.bind(this))} 

也可以通过传递第二个参数来完成这个function,因为onClick事件使用本地的这个map函数,这个在这里是未定义的,而这个当前引用的是全局对象。

 {this.state.initialPlayers.map(function(player, index) { return( <Player name = {player.name} score = {player.score} key = {player.id} index = {index} onScoreChange = {this.onPlayerScoreChange} /> ) }),this}