在setState之前反应if / else返回

时间:2020-03-19 09:02:23

标签: javascript reactjs if-statement state infinite-loop

我想遍历功能ScoreCalc,然后返回最终的“ primeCount”并将setState primeScore返回该数字。

当ScoreCalc()在componentWillMount中运行时,

this.state.animeMax仍然为空”。 当我刷新页面时,primeScore或primeCount会更改值。 我猜是因为有时安装了“ max”状态,有时没有安装!?

如果有人有想法,请告诉我。

谢谢!

export class Quality extends Component {
    constructor (props) {
        super (props) 
            this.state = {
                primeScore: 0,
                netflixScore: 0,
                huluScore: 0,
                provider:[],
                actionMax:'',
                animeMax:'',
                childrenMax:'',
                comedyMax:'',
                documentaryMax:'',
                horrorMax:'',
                musicalMax:'',
                romanceMax:'',
                scifiMax:'',
                thrillerMax:'',
            }
            this.ScoreCalc = this.ScoreCalc.bind(this);
    }
componentWillMount (){
    axios.get('http://localhost:8001/provider')
        .then(res => this.setState({
            provider: res.data
        },()=>{this.ScoreCalc()}))
    axios.get('http://localhost:8001/provider/actionmax')
        .then(res => this.setState({actionMax: res.data}))
.....10 more axios requests to setState for other "max"....

}
ScoreCalc (){
        let primeCount = 0
            if(this.state.provider[0].primeAction >= this.state.actionMax){
                primeCount += this.props.user.action;
                console.log(primeCount)
            } else {
                primeCount += (this.props.user.action*this.state.provider[0].primeAction/this.state.actionMax)
            }

            if(this.state.provider[0].primeAnime >= this.state.animeMax){
                primeCount += this.props.user.anime;
            } else {
                primeCount += this.props.user.anime*this.state.provider[0].primeAnime/this.state.animeMax;
                console.log(this.state.animeMax) //returns empty ''
                console.log(primeCount) //return infinity
            }

            if(this.state.provider[0].primeChildren >= this.state.childrenMax){
                primeCount += this.props.user.children;
            } else {
                primeCount += this.props.user.children*this.state.provider[0].primeChildren/this.state.childrenMax
            }

         console.log(primeCount); //return infinity
         this.setState({primeScore: primeCount})
}

1 个答案:

答案 0 :(得分:0)

您好像有错别字吗?

scoreCalc()中,您将像这样进行检查:

if(this.state.provider[0].primeAction >= this.actionMax){

我认为它应该是:

if(this.state.provider[0].primeAction >= this.state.actionMax){

其他if的相同吗?