简体   繁体   English

React setState在while循环中未设置状态

[英]React setState does not set state during a while loop

I want to avoid data multiplication, so i wanted to create a loop for calling my dataprovider for different site_id's. 我想避免数据重复,所以我想创建一个循环,以针对不同的site_id调用我的dataprovider。

I created a while loop and set the state values within this while loop. 我创建了一个while循环并在此while循环中设置状态值。 What I realized that from my 2 element array (I have 2 sites) only 1 is being set in the state, but the other one not. 我意识到从我的2个元素数组(我有2个站点)中,只有1个处于状态,而另一个没有。

class Dashboard extends Component {
state = {
    username: localStorage.getItem('username'),
    siteid: [{
        id: 1,
        daily: "EKdaily",
        weekly: "EKweekly",
        monthly: "EKmonthly",
        total: "EKtotal",
        },
    {
        id: 2,
        daily: "AKdaily",
        weekly: "AKweekly",
        monthly: "AKmonthly",
        total: "AKtotal",
    }]

};

componentDidMount() {
    dataProviderFactory('rest').then(
        dataProvider => {
            dataProvider(GET_ONE, 'users', {
                id: this.state.username,
            })
                .then(response => this.setState({ fullname: response.data.fullname }))

            dataProvider(GET_LIST, 'sites', {
                filter: { q: '' },
                sort: { field: '', order: '' },
                pagination: { page: 1, perPage: 1 },
            })
                .then(response => this.setState({ sites: response.data }))

            var i = 0;
            while ( i < 2 ) {
                var myId = this.state.siteid[i].id;
                var myDaily = this.state.siteid[i].daily;
                var myWeekly = this.state.siteid[i].weekly;
                var myMonthly = this.state.siteid[i].monthly;
                var myTotal = this.state.siteid[i].total;
                console.log("id", myId, myDaily, myWeekly, myMonthly, myTotal);
             dataProvider(GET_LIST, 'clicks', {
                filter: { interval: 'day', site_id: myId, count: '1', },
                sort: { field: 'date', order: 'DESC' },
                pagination: { page: 1, perPage: 50 },
            })
                .then(response => this.setState({ [myDaily]: response.data.count }))
            dataProvider(GET_LIST, 'clicks', {
                filter: { interval: 'week', site_id: myId, count: '1', },
                sort: { field: 'date', order: 'DESC' },
                pagination: { page: 1, perPage: 50 },
            })
                .then(response => this.setState({ [myWeekly]: response.data.count }))
            dataProvider(GET_LIST, 'clicks', {
                filter: { interval: 'month', site_id: myId, count: '1', },
                sort: { field: 'date', order: 'DESC' },
                pagination: { page: 1, perPage: 50 },
            })
                .then(response => this.setState({ [myMonthly]: response.data.count }))
            dataProvider(GET_LIST, 'clicks', {
                filter: { interval: 'all', site_id: myId, count: '1', },
                sort: { field: 'date', order: 'DESC' },
                pagination: { page: 1, perPage: 50 },
            })
                .then(response => this.setState({ [myTotal]: response.data.count }))
                i++;
            }
        }
    );
}

render() {
    const {
        fullname,
        username,
        EKdaily,
        EKweekly,
        EKmonthly,
        EKtotal,
        AKdaily,
        AKweekly,
        AKmonthly,
        AKtotal,
    } = this.state;
    const myPageHeader = `Udvozlunk az Admin feluleten ${fullname}!`;
    return (
        <div style={styles.flex}>
            <div style={styles.leftCol}>
                <div>
                    <Card>
                        <CardHeader title={myPageHeader} />
                        <CardContent>Bejelentkezett felhasznalo: {username}</CardContent>
                    </Card>
                </div>
                <div stlye={ { magrinTop: 200} }>
                    <Typography color="textPrimary">123.hu kattintas statisztikak</Typography>
                </div>
                <div style={styles.flex}>
                    <DisplayClick value={EKdaily} title="Napi Kattintas" />
                    <DisplayClick value={EKweekly} title="Heti Kattintas" />
                    <DisplayClick value={EKmonthly} title="Havi Kattintas" />
                    <DisplayClick value={EKtotal} title="Ossz Kattintas" />
                </div>
                 <div stlye={ { magrinTop: 20} }>
                    <Typography color="textPrimary">345.hu kattintas statisztikak</Typography>
                </div>
                <div style={styles.flex}>
                    <DisplayClick value={AKdaily} title="Napi Kattintas" />
                    <DisplayClick value={AKweekly} title="Heti Kattintas" />
                    <DisplayClick value={AKmonthly} title="Havi Kattintas" />
                    <DisplayClick value={AKtotal} title="Ossz Kattintas" />
                </div>
            </div>
        </div>
   );
}
}

Only AK* is being set in this.state, EK* not. 在此状态中仅设置了AK *,而没有设置EK *。

What do I do wrong? 我做错了什么?

Use let instead of var here: 在这里使用let代替var

Change 更改

var myId = this.state.siteid[i].id;
var myDaily = this.state.siteid[i].daily;
// ....

to

let myId = this.state.siteid[i].id;
let myDaily = this.state.siteid[i].daily;
// ....

var is scoped to the nearest function and not to the while block. var的作用域是最接近的函数,而不是while块。 It gets hoisted, and your code will be something like: 它被吊起,您的代码将类似于:

var i;
var myId;
var myDaily;

i = 0;

while ( i < 2 ) {
    myId = this.state.siteid[i].id;
    myDaily = this.state.siteid[i].daily;
}

Since dataProvider calls are asynchronous, the value of myId will be replaced with AK values by the first time call is done. 由于dataProvider调用是异步的,因此首次完成时, myId的值将被AK值替换。

dataProvider(GET_LIST, 'clicks', {
    //
})
 .then(response => this.setState({ [myWeekly]: response.data.count }))
       /* ^^ This callback runs after the while block
           By this time, myDaily === "AKdaily" */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM