Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I keep getting The class method 'componentDidMount' must be makred either 'private' 'public' or 'protected' warnings, in my tsx files?

I am not sure what I am supposed to mark my methods in my react class components. I am getting this error on these methods: componentDidMount, componentDidUpdate, componentWillUpdate and render

Here is a basic component that I have:

import * as React from 'react';

const { Component } = React;

export default class Loading extends Component<{}, {}>  {
  componentDidMount() {
    console.log('....something....');
  }
  componentDidUpdate() {
    console.log('....something....');
  }
  componentWillUpdate() {
    console.log('....something....');
  }

  render() {
    const style = {
      background: '#f5f5f5',
      height: '100%',
      padding: '20px',
      textAlign: 'center',
      transition: 'all 0.5s linear',
      width: '100%'
    };
    return (
      <div id='app-loader' className='rounded' style={style}>
        <div className='loader large block rounded'>Loading...</div>
      </div>
    );
  }
}

I can't put private render() etc because that breaks the component.

like image 919
Amir Avatar asked Dec 22 '17 18:12

Amir


People also ask

How do you avoid React componentDidMount being called multiple times?

React components call componentDidMount only once by default. You can only run the component again if you delete the component or change the key prop value. Let's look at an example where a React component only triggers componentDidMount() once.

What triggers componentDidMount?

Render JavaScript with Initial Render The componentDidMount() method will be triggered as soon as the component is mounted or inserted into the DOM. The basic syntax to use componentDidMount() is looks like this. This method used widely by developers because it loads immediately once the component is mounted.

Why does componentDidUpdate keep getting called?

ComponentDidUpdate is an update LifeCycle Hook, this will get triggered when there is something is changed in the component State or Props. Coming to your code: You are calling a handler showPosts to setState, that will again trigger the update lifecycle. This will lead to an infinite loop.

Why is componentDidMount called multiple times?

Are you seeing your React component calling the componentDidMount lifecycle multiple times? The answer to this problem is to avoid conditional rendering, and avoid adding the React prop key to the component.


1 Answers

This is the tslint member-access rule.

In tslint.json, change:

"member-access": true

To:

"member-access": [true, "no-public"] // Or false. Read the rule and see what you want.
like image 154
David Sherret Avatar answered Oct 06 '22 04:10

David Sherret