简体   繁体   中英

"this is undefined" in nested return statement

I am trying to pass some props mapObject={this.props.mapObject} details={this.props.parsedData.categories[key] through to another another component Item but I am getting TypeError: this is undefined

The props are passed through correctly as I am able to access them on the first line where I am calling mapObject . It is only in the nested return that I can't seem to access them. My code is below.

class List extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            this.props.mapObject(this.props.parsedData.categories, function (key, value) {
                return (
                    <div id="dropdown">
                        <div id="category-cirle"><center>{key[0].toUpperCase() + key[1]}</center></div>
                        <div id="dropdown-content">
                            <Item key={key} mapObject={this.props.mapObject} details={this.props.parsedData.categories[key]} />
                        </div>
                    </div>
                );
            })
        );
    }
}

How do I pass the props through to Item ?

You're using a function as the second argument of mapObjects , so this in the function is not referring to your component class. Try using arrow syntax instead, which will retain the context of this :

this.props.mapObjects(this.props.parsedData.categories, (key, value) => {
    return ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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