如果/否则返回setState之前的反应

问题描述 投票:0回答:1

我想通过Function 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})
}

javascript reactjs if-statement state infinite-loop
1个回答
0
投票
scoreCalc()中,您正在像这样检查:

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

我认为应该是:

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

与其他if的相同?

© www.soinside.com 2019 - 2024. All rights reserved.