【发布时间】:2018-05-25 23:12:17
【问题描述】:
我有一个类组件如下:
class App extends Component {
constructor(props){
super(props);
this.state = {
abc: '',
someQuery: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidUpdate(){
fetch(`/someLink/${this.state.abc}`)
.then(response => {
return response.json();
}).then(data => {
this.setState({
someQuery: data.xxx
});
});
}
handleSubmit(e){
const target = e.target;
const value = target.value;
this.setState({
abc: value
})
e.preventDefault();
};
handleChange(e){
const target = e.target;
const value = target.value;
this.setState({
abc: value
});
};
render(){
return(
<form onSubmit={this.handleSubmit}>
<input name='abc' value={this.state.abc} onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
<div>{this.state.abc} is currently accessing data from {this.state.someQuery}</div>
)
}
}
如何在每次更新输入字段的值并单击提交按钮时运行componentDidUpdate()?
上面调用了生命周期,但是由于setState也在handleChange()中,生命周期在我输入内容的那一刻被调用,而不是等到提交按钮被点击。
从handleChange() 中删除setState 会使输入字段值不再可编辑(无法在输入字段上键入)。
我需要在生命周期中将输入字段值附加到api link,但我似乎无法找出正确的方法。
【问题讨论】:
-
在您的输入中使用 defaultValue 而不是 value。
-
为什么不在
componentDidMount中添加条件来查看表单是否已提交?
标签: javascript reactjs react-lifecycle