设置: 我有一个将数据发送给操作创建者的表单,该创建者又将其提交给API并获取结果。我想要的是表单提交成功后,用空白输入刷新表单。
这是组件的外观
import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { addNewProduct } from "../../redux/actions";
class Admin extends Component {
state = {
ProductName: ""
};
onChange = e => {
e.preventDefault()
this.setState({
[e.target.name]: e.target.value
})
}
handleProductSubmit = (event) => {
event.preventDefault();
this.props.addNewProduct(
this.state.ProductName,
);
}
render() {
return (
<div>
{/* Form ends */}
<form onSubmit={this.handleProductSubmit} autoComplete="off">
<input
type="text"
value={this.state.ProductName}
name="ProductName"
onChange={this.onChange}
/>
<button type="submit" className="btn btn-dark">
Upload Product
</button>
</form>
{/* Form Ends */}
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ addNewProduct, createNewLogin }, dispatch);
};
export default connect(null, mapDispatchToProps)(Admin);
这是console.log(this.props)的结果
location: Object { pathname: "/Home/admin", href: "http://localhost:3000/Home/admin", origin: "http://localhost:3000", … }
navigate: navigate(to, options)
length: 2
name: "navigate"
prototype: Object { … }
<prototype>: ()
这是actionCreator的外观
export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {
const productData = new FormData();
productData.append("ProductName", ProductName)
axios.post("http://localhost:4500/products/", productData,
{
headers: {
"Content-Type": "multipart/form-data",
"Authorization": localStorage.getItem("Authorization")
}
})
.then(res => {
console.log(res.data)
setTimeout(() => {
console.log("doing the timeout")
navigate("/Home/admin")}, 1500);
})
.catch(err =>
console.log(`The error we're getting from the backend--->${err}`))
};
当前行为
当我提交表单并且API返回201时,页面不会刷新,输入也不会空白
预期的行为:
当我从API收到201时,页面应该刷新,输入应该为空白。
请帮助我如何实现这一目标。
答案 0 :(得分:0)
使用导航键移动相同的网址或页面不会重新安装页面并重置字段值。
更好的是,您实际上是从动作创建者那里返回了一个诺言,然后自己重置状态
export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {
const productData = new FormData();
productData.append("ProductName", ProductName)
return axios.post("http://localhost:4500/products/", productData,
{
headers: {
"Content-Type": "multipart/form-data",
"Authorization": localStorage.getItem("Authorization")
}
})
.then(res => {
console.log(res.data)
})
.catch(err =>
console.log(`The error we're getting from the backend--->${err}`))
};
在组件中
handleProductSubmit = (event) => {
event.preventDefault();
this.props.addNewProduct(
this.state.ProductName,
).then(() => {
this.setState({ProductName: ""})
});
}