I have been asked this question by someone. I was not able to give a correct answer. Could you please help me out? Why we can't access the value of event (e) in setTimeout?
import React from 'react';
import { render } from 'react-dom';
class App extends React.Component{
state = {
number: 1,
}
handleNumber = (e) => {
console.log(e)
setTimeout(() => {
console.log(e) // It becomes null here.
if(e) {
this.setState({number: this.state.number + 1})
console.log(this.state.number)
}
}, 10)
}
render() {
return (
<div>
<button onClick={this.handleNumber}>Hello world</button>
</div>
)}
}
render(<App />, document.getElementById('root'));
You should be able to access the event, more likely you're trying to access a property of the synthetic event like e.type
or something like that. Because React reuses the synthetic event object, all properties of the event become null once the handleNumber
function returns. See the docs for more info.
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.