reactjs - 反应类型错误:this.state 为空
问题描述
我正在创建一个联系人管理器应用程序,我可以添加和删除联系人,但我还没有添加编辑功能,我尝试构建一个编辑组件来编辑我的联系人,但是当我运行编辑时组件我收到一条错误消息,说“this.state is null”,这指向编辑组件...这就是我的编辑组件的样子;
class EditContact extends Component {
changeFirstName = (event) => {
const { contact } = this.state;
const newContact ={
...contact,
firstName: event.target.value
};
this.setState({ contact: newContact });
}
changeLastName = (event) => {
const { contact } = this.state;
const newContact ={
...contact,
lastName: event.target.value
};
this.setState({ contact: newContact });
}
changeEmail = (event) => {
const { contact } = this.state;
const newContact ={
...contact,
email: event.target.value
};
this.setState({ contact: newContact });
}
changePhone = (event) => {
const { contact } = this.state;
const newContact ={
...contact,
phone: event.target.value
};
this.setState({ contact: newContact });
}
changeBalance = (event) => {
const { contact } = this.state;
const newContact ={
...contact,
balance: event.target.value
};
this.setState({ contact: newContact });
}
render() {
return (
<>
<Navbar />
<div>
<div className="row">
<div className="col-md-6">
<Link to="/" className="btn btn-link">
<i className="fas fa-arrow-circle-left"></i>Back To Contacts
</Link>
<br></br>
<p>
Need to Edit a few things about your Contacts, Go ahead and make all those changes here...!!!
</p>
<input
type="text"
onChange={this.changeFirstName}
value={this.state.contact.firstName}
/>
<input
type="text"
onChange={this.changeLastName}
value={this.state.contact.lastName}
/>
<input
type="text"
onChange={this.changeEmail}
value={this.state.contact.email}
/>
<input
type="text"
onChange={this.changePhone}
value={this.state.contact.phone}
/>
<input
type="text"
onChange={this.changeBalance}
value={this.state.contactbalance}
/>
</div>
</div>
</div>
</>
);
}
}
解决方案
您需要在类的构造函数中启动状态:
class EditContact extends Component {
constructor(props) {
super(props) <== Not needed in latest react
this.state = {
contact: {},
...other
}
}
// Rest of your component
推荐阅读
- android - 如何修复我的颤振应用程序与我的华为的连接?
- c - C 编程:聊天机器人阅读几个问题和答案。如何创建多个键和值?
- airflow - Airflow catch 设置为 false 不能通过配置和代码工作
- c - 多个`FILE`s附加到同一个文件
- java - Producer-Consumer:缓冲区接收来自同一个Producer的n条连续消息
- javascript - 如何在不知道 id 的 fire-base 数据库中查找嵌套值?
- javascript - Coinmarketcap 在拉动价格时给出 #N/A 和 Loading.. 错误
- php - 如何在 Ubuntu 14.04 上的 PHP 7.2 中安装/启用 Tidy 扩展?
- c# - 偶尔会出现错误:“请求已中止:无法创建 SSL/TLS 安全通道。”
- angular - 如何在 Angular 中组织路由?