简体   繁体   English

使用地图时反应“无法读取未定义的属性”

[英]React 'cannot read property of undefined' when using map

I'm making a very basic React app from teamtreehouse.com, and I'm constantly encountering我正在从 teamtreehouse.com 制作一个非常基本的 React 应用程序,我经常遇到

"TypeError: Cannot read property 'onPlayerScoreChange' of undefined" “类型错误:无法读取未定义的属性‘onPlayerScoreChange’”

even though I'm binding my functions correctly (I think)即使我正确地绑定了我的功能(我认为)

'onPlayerScoreChange' Is a method in the Grandparent component which executes when a user hits a '+' or '-' button to change a player's score. 'onPlayerScoreChange'Grandparent组件中的一种方法,当用户点击“+”或“-”按钮以更改玩家的分数时执行。

It would be really helpful if someone could explain what is wrong, because I think I am setting this.onPlayerScoreChange = this.onPlayerScoreChange.bind(this) in the great grandparent's constructor.如果有人能解释出什么问题,那将非常有帮助,因为我想我在曾祖父母的构造函数中设置this.onPlayerScoreChange = this.onPlayerScoreChange.bind(this)

Parent component:父组件:

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>
    )
}}

(Component has default props for title) (组件有标题的默认道具)

Child component:子组件:

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>
)
}}

Grandchild component:孙组件:

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>
)}}

Thank you!谢谢!

You have not done binding for the map function where you are using onScoreChange = {this.onPlayerScoreChange} ,您尚未在使用onScoreChange = {this.onPlayerScoreChange}的地图功能上完成绑定,

you can either use bind or arrow functions for binding您可以使用绑定或箭头函数进行绑定

PS Binding is needed because the context of the map function is different from the React Component context and hence this inside this function won't be Referring to the React Components this and thus you can't access that properties of the React Component class.需要 PS 绑定,因为 map 函数的上下文与 React Component 上下文不同,因此this函数内部的 this 不会引用 React Components this ,因此您无法访问 React Component 类的属性。

With Arrow function:带箭头功能:

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

With bind带绑定

   {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))}

Can also be done by passing second argument as this to map function as onClick event uses local this of map function which is undefined here and this currently refers to the global object.也可以通过将第二个参数作为 this 传递给 map 函数来完成,因为 onClick 事件使用此处未定义的 map 函数的本地 this,并且 this 当前指的是全局对象。

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

sometimes it is quite easy and it all depends on how you declare your loop有时这很容易,这完全取决于您如何声明循环

example you will get this error if you try to do something like this var.map(function(example, index) {}例如,如果您尝试执行类似这样的操作,您将收到此错误 var.map(function(example, index) {}

but if you call the new function within the map with this但是如果你用这个调用地图中的新函数

this.sate.articles.map(list => 
{<a onClick={() => this.myNewfunction()}>{list.title}</a>)}

the second loop will get you out of the undefined error第二个循环会让你摆脱未定义的错误

and dont forget to bind your new function并且不要忘记绑定您的新功能

//This should be declared befor map function //这应该在地图函数之前声明

const thObj = this; const thObj = 这个;

this.sate.articles.map(list => {<a onClick={() => thObj.myNewfunction()}>{list.title})} this.sate.articles.map(list => {<a onClick={() => thObj.myNewfunction()}>{list.title})}

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

相关问题 尝试使用 react-leaflet-choropleth map choropleth 时出错:无法读取未定义的属性“地图” - Error when trying to map a choropleth using react-leaflet-choropleth: Cannot read property 'map' of undefined TypeError:无法使用 REDUX 读取 REACT 中未定义的属性“映射” - TypeError: Cannot read property 'map' of undefined in REACT using REDUX 使用React的新功能:TypeError:无法读取未定义的属性“ map” - New using React: TypeError: Cannot read property 'map' of undefined 在 React 中使用 2 个下拉菜单。 无法读取未定义的属性“地图” - Using 2 dropdowns in React. Cannot read property 'map' of undefined 无法使用反应钩子读取未定义的属性“地图” - Cannot read property 'map' of undefined with react hooks React-TypeError:无法读取未定义的属性“ map” - React - TypeError: Cannot read property 'map' of undefined 无法读取未定义的属性“映射”“反应中的错误 - Cannot read property 'map' of undefined" Error in React React App 无法读取未定义的属性“地图” - React App cannot read property 'map' of undefined 无法读取未定义REACT的属性“地图” - Cannot read property 'map' of undefined REACT React JS 无法读取未定义的属性“地图” - React JS cannot read property 'map' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM