我收到此错误Uncaught TypeError: Cannot read property 'state' of undefined每当我在 AuthorForm 的输入框中键入任何内容时。我将 React 与 ES7 一起使用。
错误发生在 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