简体   繁体   中英

Using Local Methods within React Lifecycle Methods

I was curious to see if the following code would work:

 class App extends React.Component { componentDidMount() { logger('mount') } componentDidUpdate() { logger('update') } logger = x => { console.log(x) } render() { return ( <div className='container'> </div> ) } } ReactDOM.render(<App />, document.getElementById('app')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

I've been working with React for a while now and never came across a reason to use a local method within a lifecycle method, but I thought I'd try it out today out of curiosity. I haven't been able to find any designated explanation as to why this might not work. Is it the order in which the app is initialized and it's just not seeing the it when it's called, or is it something basic that I'm not thinking of?

我相信这可能就像将this.logger('mount')this.logger('update') logger('mount')logger('update') this.logger('mount')一样简单:)

You need to prepend your function calls with this. to get access to local methods:

 class App extends React.Component { componentDidMount() { this.logger('mount') } componentDidUpdate() { this.logger('update') } logger = x => { console.log(x) } render() { return ( <div className='container'> </div> ) } } ReactDOM.render(<App />, document.getElementById('app')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

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