每当我在AuthorForm的输入框中输入任何内容时,我都会收到这个错误:无法读取未定义状态的TypeError属性‘’。我正在对ES7使用React。
错误出现在ManageAuthorPage中setAuthorState函数的第3行。不管那一行代码,即使我在setAuthorState中放入一个console.log(this.state.author),它也会在console.log处停止并发出错误。
在互联网上找不到其他人的类似问题。
下面是ManageAuthorPage代码:
import React, { Component } from 'react';
import AuthorForm from './authorForm';
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
setAuthorState(event) {
let field = event.target.name;
let value = event.target.value;
this.state.author[field] = value;
return this.setState({author: this.state.author});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.setAuthorState}
/>
);
}
}
export default ManageAuthorPage
下面是AuthorForm代码:
import React, { Component } from 'react';
class AuthorForm extends Component {
render() {
return (
<form>
<h1>Manage Author</h1>
<label htmlFor="firstName">First Name</label>
<input type="text"
name="firstName"
className="form-control"
placeholder="First Name"
ref="firstName"
onChange={this.props.onChange}
value={this.props.author.firstName}
/>
<br />
<label htmlFor="lastName">Last Name</label>
<input type="text"
name="lastName"
className="form-control"
placeholder="Last Name"
ref="lastName"
onChange={this.props.onChange}
value={this.props.author.lastName}
/>
<input type="submit" value="Save" className="btn btn-default" />
</form>
);
}
}
export default AuthorForm
发布于 2016-02-09 17:14:53
确保在构造函数中第一件事就是调用super()
。
您应该为setAuthorState
方法设置this
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
constructor(props) {
super(props);
this.handleAuthorChange = this.handleAuthorChange.bind(this);
}
handleAuthorChange(event) {
let {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
另一种基于arrow function
的替代方案
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
handleAuthorChange = (event) => {
const {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
发布于 2016-02-09 17:14:48
您必须将事件处理程序绑定到正确的上下文(this
):
onChange={this.setAuthorState.bind(this)}
https://stackoverflow.com/questions/35287949
复制相似问题