我是React和Axios的新手。我想获取客户数据,但是当他们的地址为空时,出现错误
“ TypeError:无法读取未定义的属性'street'。”
客户有地址时,一切正常。我有什么办法可以在不接触后端的情况下完成这项工作?
class Account extends Component {
constructor(props) {
super(props);
this.state = {
orders: []
};
componentDidMount() {
axios.get(`https://api.mysite.com/customer`)
.then(res => {
const orders = res.data;
this.setState({ orders });
console.log(orders);
})
}
render() {
return (
<div className="input left">
{this.state.orders.map(order => <Input className="name" type="text" readOnly value={order.name} />)}
{this.state.orders.map(order => <Input className="email" type="text" readOnly value={order.email} />)}
{this.state.orders.map(order => <Input className="password" type="text" readOnly value="*******" />)}
{this.state.orders.map(order => <Input className="address" type="textarea" readOnly value={order.address[0].street} />)}
{this.state.orders.map(order => <Input className="phone" type="text" readOnly value={order.address[0].phone} />)}
</div>
);
}
}
对不起,如果名称令人困惑,我只是从/ order页面复制了它
这是WORKING帐户中的console.log(订单)
0:
address: Array(1)
0:
city: "Jakarta Utara"
country: "Indonesia"
created_at: "2019-05-21 10:54:19"
customer_id: "c8ca7ce0-7bb6-11e9-90f8-e1b44f49dcc3"
id: "c8cc3910-7bb6-11e9-b13b-537042a9805b"
name: "fendi"
phone: "0812308123"
postal_code: "14420"
province: "DKI Jakarta"
street: "test"
updated_at: "2019-05-21 10:54:19"
__proto__: Object
length: 1
__proto__: Array(0)
created_at: "2019-05-21 10:54:19"
email: "test@gmail.com"
email_verified_at: null
id: "c8ca7ce0-7bb6-11e9-90f8-e1b44f49dcc3"
name: "test"
role_id: "a022e290-7bb6-11e9-9fb6-09e2f5236d0a"
updated_at: "2019-05-21 10:54:19"
这是NOT WORKING帐户中的console.log(订单)
0:
address: Array(0)
length: 0
__proto__: Array(0)
created_at: "2019-05-21 10:53:11"
email: "test@admin.com"
email_verified_at: "2019-05-21 10:53:11"
id: "a02279a0-7bb6-11e9-8711-515da07aadda"
name: "Alisha Stamm"
role_id: "a0156ca0-7bb6-11e9-8ba3-43dcab891f96"
updated_at: "2019-05-21 10:53:11"
可以看出,引发错误的帐户没有任何地址(例如街道名称),我叫.address.street 未定义
请帮助,谢谢!
答案 0 :(得分:1)
您可以尝试这样
{this.state.orders.map(order => <Input className="address" type="textarea" readOnly value={order.address.length>=0 ? order.address[0].street : ""} />)}
答案 1 :(得分:0)
{ this.state.orders.map(({ address = [{}] }) => <Input className="address" type="textarea" readOnly value={address[0].street} />) }
{ this.state.orders.map(({ address = [{}] }) => <Input className="phone" type="text" readOnly value={address[0].phone} />) }
您可以销毁订单对象并为您的对象分配初始值,以使此类条件不会失败。更多信息,请点击https://javascript.info/destructuring-assignment
答案 2 :(得分:0)
是在渲染方法中使用三元语句
{this.state.order.street ? (
{this.state.orders.street}
) : (这里没有可显示的街道
)}