gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'street' of undefined

转载 作者:行者123 更新时间:2023-11-30 13:56:55 27 4
gpt4 key购买 nike

我的程序加载了一个用户列表(带有 jsonplaceholder 数据),我试图使该数据可编辑,但出现错误:

TypeError: Cannot read property 'street' of undefined

有人可以帮忙吗?

class Users extends React.Component {
constructor(){
super();
this.state = {
users: [],
displayList: 'block',
displayForm: 'none',
edit: false,

userEdit: {
id: null,
name: "",
email: "",
address: {
street: "",
suite: "",
city: "",
zipcode: ""
},
phone: ""
}
}
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
}

componentDidMount(){
this.getUsersList();
}

getUsersList(){ ... }

getUserEdit(){ ... }

handleClick(id){ ... }

我很难在 handleChange 函数中编写代码,也可能是错误的

handleChange(event){
const {name, value} = event.target
this.setState({
userEdit:{
[name]: value
}
})
}

render(){
if (this.state.edit === false) {
return (
<UsersList
users = {this.state.users}
displayList = {this.state.displayList}
handleClick = {this.handleClick}
/>
);
}

else {
this.getUserEdit();
return(
<UserEdit
user = {this.state.userEdit}
displayForm = {this.state.displayForm}
handleChange = {this.handleChange}
handleClick = {this.handleClick}
/>
)
}
}
}

在 UserEdit.js 中

function UserEdit(props){
return(
<ul>
<div style={{display: props.displayForm.form}} key={props.user.id}>
       <form>
         <h2>{props.user.name} </h2>
<p>Email:
<input
type="text"
name="email"
value = {props.user.email}
className="form-control"
onChange={(event) => props.handleChange(event)}
/>
</p>
<p>Address: </p>
<ul>
<li>Street:
<input
type="text"
name="street"
value = {props.user.address.street}
className="form-control"
onChange={(event) => props.handleChange(event)}
/>
</li>
<li>Suite:
<input
type="text"
name="suite"
value = {props.user.address.suite}
className="form-control"
onChange={(event) => props.handleChange(event)}
/>
</li>
<li>City:
<input
type="text"
name="city"
value = {props.user.address.city}
className="form-control"
onChange={(event) => props.handleChange(event)}
/>
</li>
<li>ZipCode:
<input
type="text"
name="zipcode"
value = {props.user.address.zipcode}
className="form-control"
onChange={(event) => props.handleChange(event)}
/>
</li>
</ul>
<p>Phone:
<input
type="text"
name="phone"
value = {props.user.phone}
className="form-control"
onChange={(event) => props.handleChange(event)}
/>
</p>
       </form>
<button onClick={() => props.handleClick()}> Save </button>
<hr></hr>
       </div>
</ul>
)
}

最佳答案

您需要检查address 是否包含street。在同一行,您还应该检查 user 是否包含 address

一次类轮检查可以是:

value = { props.user && props.user.address && props.user.address.street ? props.user.address.street : ''

关于javascript - 类型错误 : Cannot read property 'street' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57079164/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com