简体   繁体   中英

How can I setState in componentDidUpdate?

I'm trying to set the state based on API data. 'own' is a field in my API and it contains the Boolean value "true"... I'm storing the data I'm getting from the API in an object called passedXdayPassObj... I want to set the value of checked property based on the API value of "own"..But it doesn't happen.. Following is my code...

 componentDidUpdate(prevProps) {
        let passedXdayPassObj;
        const { xDayPass } = this.props;

        if (xDayPass.xDay && xDayPass.xDayLoading === false && JSON.stringify(xDayPass.xDay) !== JSON.stringify(prevProps.xDayPass.xDay) && !this.props.pathname.includes("createChannel") && !this.state.isSubmit) {
            passedXdayPassObj = {
                own: xDayPass.xDay.own,
                totalCount: xDayPass.xDay.totalCount,
                totalValue: xDayPass.xDay.totalValue,
                purchaseStart: moment(xDayPass.xDay.purchaseStart).format(),
                purchaseEnd: moment(xDayPass.xDay.purchaseEnd).format(),
                price: xDayPass.xDay.price,
                restricted: false,
                utilizeStart: xDayPass.xDay.utilizeStart,
                utilizeEnd: xDayPass.xDay.utilizeEnd,

            }

            if (this.props.location && this.props.location.state && this.props.location.state.view || this.props.location.state.edit) {
                this.props.initialize(passedXdayPassObj);
            }

            if (passedXdayPassObj && passedXdayPassObj.own) {
                this.setState({
                    checked: passedXdayPassObj.own
                });
            }
        }
    }

You don't do state updates inside of compoonentDidUpdate() lifecycle methods it results in too many recursions ultimately crashing your app.

Shift the same code inside of componentDidMount() and everything will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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