I want to search for people. An array of data is stored in the redux store. I'm trying to perform a search, but an error occurs.
Cannot read property 'searchInput' of undefined
What could be the problem?
searchHandler(){
console.log('findUser', this.searchInput.value);
this.props.onFindPeople(this.searchInput.value)
}
I add an example code
You lost the context of this
to the event handler.
You can either use an arrow function (that uses a lexical context for this
):
searchHandler = () => {
console.log("findUser", this.searchInput.value);
this.props.onFindPeople(this.searchInput.value);
}
Or bind it to the class like this:
constructor(props){
super(props);
this.searchHandler = this.searchHandler.bind(this);
}
We do it in the constructor
because it will run only once.
You are not binding the function. You need to bind it in constructor like below. Binding is required in order to access this and access state, props and modifying the state.
Please note you need to bind it only in constructor not anywhere else in the component
constructor(props){
super(props);
this.searchHandler = this.searchHandler.bind(this);
}
searchHandler(){
console.log('findUser', this.searchInput.value);
this.props.onFindPeople(this.searchInput.value);
}
Or you can also use arrow function as Sagiv mentioned in his answer.
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.