我正在尝试根据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
});
}
}
}
将相同的代码移到componentDidMount()内部,一切正常。