我收到此错误 Uncaught TypeError: 每当我在AuthorForm的输入框中键入任何内容时,都 无法读取未定义的属性“ state” 。我在ES7中使用React。
该错误发生 在ManageAuthorPage中的setAuthorState函数的第三行 。无论哪行代码,即使我将console.log(this.state.author)放在setAuthorState中,它也将在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
确保super()在构造函数中首先调用。
super()
你应该设置this的setAuthorState方法
this
setAuthorState
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:
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} /> ); } }