简体   繁体   English

在React Lifecycle方法中使用局部方法

[英]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. 我已经在React上工作了一段时间,但从未遇到过在生命周期方法中使用本地方法的原因,但是我认为出于好奇,我今天会尝试使用它。 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. 您需要为此添加函数调用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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