I'm asking a basic question but I'm a noob which couldn't even find the answer in google so please be gentle ๐. I'm trying to use setstate and I have no idea why my state continue to be empty. Here is the code:
import React, {Component} from 'react';
import Ball from './Ball'
class Lottery extends Component{
constructor(props){
super(props);
this.state = { nums : []};
this.RenderNums = this.RenderNums.bind(this);
this.RenderNums();
}
RenderNums(){
let ballnum = this.props.ballnum;
let maxnum = this.props. maxnum;
let arrnums = Array.from({length: ballnum}, () => Math.floor(Math.random() * maxnum) +1);
console.log(arrnums);
this.setState({nums : arrnums});
}
I'm trying to put my random number array in the state, for that I'm calling a function in the constructor, but after npm start and looking at the dev tools my state nums is an empty array. The random numbers array is created just fine and being printed to the console. Someone can tell what am I doing wrong by looking at the code? If necessary I'll try to put it on codepen.
You should not call setState or any side effect in constructor, as mentioned in the docs:
You should not call setState() in the constructor(). Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor
Instead, assign the initial state directly or use a dedicated lifecycle, you should try componentDidMount.
class Lottery extends Component {
constructor(props) {
super(props);
this.state = {
nums: Array.from(
{ length: this.props.ballnum },
() => Math.floor(Math.random() * this.props.maxnum) + 1
),
};
}
// or
RenderNums = () => {...}
componentDidMount() {
this.RenderNums();
}
}
Put this.RenderNums(); call inside componentDidMount () {} method.
class Lottery extends Component{
constructor(props){
super(props);
this.state = { nums : []};
this.RenderNums = this.RenderNums.bind(this);
//this.RenderNums();
}
componentDidMount(){
this.RenderNums();
}
RenderNums(){
let ballnum = this.props.ballnum;
let maxnum = this.props. maxnum;
let arrnums = Array.from({length: ballnum}, () => Math.floor(Math.random() * maxnum) +1);
console.log(arrnums);
this.setState({nums : arrnums});
}
componentDidMount is equivalents useEffect in function components. you should not call setState inside Constructor.