【发布时间】:2020-01-11 11:13:01
【问题描述】:
我正在尝试清除我的 react-redux 组件中的表单。我知道我应该能够在提交后使用 setState() 清除它们,但是由于我将所有数据作为道具接收(通过 redux 存储),是否有一种简单的方法可以在组件本身内执行此操作?
class Postform extends Component {
constructor(props){
super(props)
this.state={
propertyName: ' enter name ',
footage: ' size in sqft ',
address: ' full address ',
price: ' $ 00.00 '
}
}
onChange =(e)=>{
this.setState({ [e.target.name] :e.target.value});
}
onSubmit = (e) =>{
e.preventDefault()
const newListing = {
propertyName: this.state.propertyName,
footage: this.state.footage,
address: this.state.address,
price: this.state.price
}
this.props.newProperty(newListing)
// my attempt to reset the state of the form (unsure how to accomplish this?)
this.setState({
propertyName: '',
footage: '',
address: '',
price: ''
})
};
render() {
return (
<div className="form">
<h2>Add Listing</h2>
<form onSubmit = {this.onSubmit}>
<div>
<label>your listing name</label><br/>
<input name="propertyName" type="text" onChange={this.onChange} placeholder={this.state.propertyName} />
</div>
<div>
<label>listing size </label><br/>
<input name="footage" onChange={this.onChange} placeholder={this.state.footage} />
</div>
<div>
<label>listing location </label><br/>
<input name="address" onChange={this.onChange} placeholder={this.state.address} />
</div>
<div>
<label>desired price </label><br/>
<input name="price" onChange={this.onChange} placeholder={this.state.price} />
</div>
<br/>
<button className="submitbtn" type="submit">Submit</button>
</form>
</div>
)
}
}
Postform.propTypes = {
newProperty: PropTypes.func.isRequired,
new: PropTypes.object
}
const mapStateToProps = state =>({
listings: state.listings.properties,
new: state.listings.newListing
});
export default connect(mapStateToProps, {newProperty})(Postform)
我在网上查了一下,找到了一些解决方案。我想看看是否有人可以根据我的代码告诉我是否有实现此目的的首选方法?
这里所有不同的方法我都不确定我应该根据我的组件使用哪种方法:https://redux-form.com/6.0.0-alpha.7/docs/faq/howtoclear.md/
【问题讨论】:
标签: javascript reactjs forms react-redux state