【发布时间】:2016-05-19 04:42:28
【问题描述】:
每当我在 AuthorForm 的输入框中键入任何内容时,我都会收到此错误 Uncaught TypeError: Cannot read property 'state' of undefined。我在 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
【问题讨论】:
-
您不得直接修改状态。有
asynchronoussetState(...) 为此。我正在写这个声明this.state.author[field] = value;。 -
只需将
setAuthorState(event) {...};转换为setAuthorState = (event) => {...};否则您必须明确绑定(this)
标签: javascript reactjs ecmascript-6 ecmascript-2016