Component not rendering....again

My component was rendering perfectly fine, but when I added the last two properties to the element, the component stopped rendering properly. I tested it by typing one part at a time, and it seems like it renders perfectly fine until I add a number in the bracket to pull an element out, in my case Math.floor(Math.random() * 3). I tried using a simple int as well, but it didn’t like that either.

class RQMApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      quotes: ["9 + 10 = 21", "waboody daboody", "I'm breathin' different"],
      authors: ["Anonymous", "Fresh215", "Ace"],
      currentQuote: this.quotes[Math.floor(Math.random() * 3)],
      currentAuthor: this.authors[this.quotes.indexOf(this.currentQuote)]
    }
  }
  
  newQuote(){
    
  }
  
  render() {
    return (
      
      <div id="quote-box">
        <p>bklkkllklklkdfklppp</p>
      </div>
    );
  }
}

ReactDOM.render(
  <RQMApp />,
  document.getElementById('root')
);

You’re referencing the state inside the state and it’ll break. What does this refer to when it’s inside the state? Unless you’re extremely confident about how React, internally, deals with updating and referencing that object, it’s not going to be safe to then add another layer of internal references to it.

state = {
  quotes: ["9 + 10 = 21", "waboody daboody", "I'm breathin' different"],
  authors: ["Anonymous", "Fresh215", "Ace"],
  currentQuote: ""
  currentAuthor: ""
};

setCurrentQuote = () => {
  this.setState((currentState)  => {
    const randIndex = Math.floor(Math.random() * current state.quotes.length);
    const currentQuote = currentState.quotes[randIndex];
    const currentAuthor = currentState.authors[randIndex];

    return { currentQuote, currentIndex };
  });
};
1 Like

I was under the assumption that it was the same as using the this keyword in any basic Javascript object. Thank you.

Using the method you created, how would I call setCurrentQuote() on page load? Is it good practice to make a method call in the constructor?

No, for class components you use the componentDidMount lifecycle method: component initialises >> that method is called >> in it you can set the state.

componentDidMount() {
  this.setCurrentQuote();
}

This

And this

Are important

1 Like