Uncaught TypeError: Cannot read the 'bind' property from undefined

I get this error when I try to call a function onClick <li onClick={this.props.selectItem.bind(this, item.id)} key={index}>:

export default class List extends React.Component {
    getState(props) {
        const key = props.params.key;
        return {
            key : key,
            list: Store.getList()
        }
    }

    constructor(props) {
        super(props);
        this.state = this.getState(props);
    }

    renderList(item, index) {
        return <li onClick={this.props.selectItem.bind(this, item.id)} key={index}>{item.name}</li>;
    }

    render() {
        return (
            <ul>
                {this.state.list.map(this.renderList.bind(this))}
            </ul>
        )
    }
}

And I have a parent:

export default class App extends React.Component {
    selectItem(item) {
        alert(item);
    }

    render() {
        return (
            <div>
                <List selectItem={this.selectItem} params={someParams} />
            </div>
        );
    }
}
+4
source share
2 answers

You should pass nullinstead thisfor bindwhen binding methods are passed from source components.

So it this.props.selectItem.bind(this, item.id)becomes this.props.selectItem.bind(null, item.id).

0
source

In the constructor, run the command this.renderList = this.renderList.bind (this);

0
source

Source: https://habr.com/ru/post/1625383/


All Articles