【发布时间】:2020-05-12 23:30:30
【问题描述】:
我有一个名为 App 的 React 组件,它应该显示基于 HTML 表单的内容。每次用户提交表单时,App 的状态都应该适应。起初我是这样实现我的课程的:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {technologies: [], subject: ''};
this.updateSubject = this.updateSubject.bind(this);
this.updateTimeline = this.updateTimeline.bind(this);
}
componentDidMount() {
this.updateTimeline();
}
updateSubject(event) {
this.setState({subject: event.target.value});
}
updateTimeline() {
fetch('/timeline?subject=' + this.state.subject)
.then(res => res.json())
.then(technologies => this.setState({technologies: technologies}));
}
render() {
return <div>
<form id="subject" onSubmit={this.updateTimeline}>
<label>
Subject:
<input type="text" value={this.state.subject} onChange={this.updateSubject} />
</label>
<input type="submit" value="Submit" />
</form>
<Timeline techs={this.state.technologies} />
</div>;
}
}
但是,我发现这样每次表单提交都会重新加载页面(或至少调用 App 构造函数)......这是不幸的,因为 App 的状态被重置为空字符串(参见构造函数的第二行)。所以我尝试在updateTimeline方法中添加一个event参数,并在调用fetch之前调用event.preventDefault();:
updateTimeline(event) {
event.preventDefault();
fetch('/timeline?subject=' + this.state.subject)
.then(res => res.json())
.then(technologies => this.setState({technologies: technologies}));
}
这给了我在控制台中的TypeError: event is undefined。为什么会这样?
【问题讨论】:
-
??
updateTimeline()的定义中没有event参数 -
那是因为在
componentDidMount中你调用它时没有传递任何东西。 -
正如我的问题中所指定的,我当然尝试将
event参数添加到updateTimeline的签名中。我的问题是,即使在添加了event参数之后,我也会得到TypeError: event is undefined。我可以通过编辑来澄清我的问题。
标签: javascript reactjs forms