我如何在componentDidUpdate中设置状态?

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

我正在尝试根据API数据设置状态。 “ own”是我的API中的一个字段,它包含布尔值“ true” ...我将从API获取的数据存储在一个名为passXdayPassObj的对象中...我想基于“ own”的API值设置checked属性的值。但这不会发生。以下是我的代码...

 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
                });
            }
        }
    }
reactjs react-redux
1个回答
0
投票
您不会在compoonentDidUpdate()生命周期方法内进行状态更新,这会导致太多的递归最终使您的应用程序崩溃。

将相同的代码移到componentDidMount()内部,一切正常。

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