未捕获类型错误:无法读取未定义的属性'Active'



我的SPA中有一个帐户页面,我目前正在尝试使用数据库中的信息填充该页面。

我已经使用邮递员查看我尝试访问的属性是否可用。以及我能够从同一元素访问另一个属性。

来自邮递员的 JSON

{
"newsSubscription": {
"SubscriptionID": "1",
"ObjectID": "00000000-0000-0000-0000-000000000000",
"OrganizationNumber": null,
"CompanyName": null,
"Active": true,
"SubscriptionType": 1,
"ObjectType": 1
},
"Subscriptions": [],
"Email": "email@email.com"
}

我正在使用 axios 访问 API。我能够获取电子邮件地址,但似乎无法访问"活动"的真/假,这将确定复选框是否被选中。

class Example extends React.Component {
state = {
emailAddress: [],
}
componentDidMount() {
axios.get(
'http://api',
{ withCredentials: true }
)
.then(res => {
const emailAddress = res.data;
this.setState({ emailAddress });
})
//error handling
}
render() {
return (
// Removed for simplicity
<Typography>The registered e-mail address for your account is <b>{this.state.emailAddress.Email}</b></Typography>
<Checkbox
checked={this.state.emailAddress.newsSubscription.Active}
value="email_notifications"
color="primary"
/>
);
}
}

我希望 API 属性"活动"根据 API 调用的真/假响应选中或取消选中复选框。

state = {
emailAddress: [],
}

你的状态很混乱。你的state.emailAddress是一个数组,但你把它当作一个对象:this.state.emailAddress.newsSubscription.

您的 API 为您提供一个对象或数组?我认为你的问题就在这里。

请在渲染部分添加

console.log(this.state.emailAddress);

看看会发生什么。也许数据如何到达存在问题,这就是它失败的原因。

相关内容

最新更新