访问路由器刷新页面



设置:我有一个表单,它将数据发送给一个动作创建者,后者又提交给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时,页面应该刷新,输入应该为空。

请帮助我如何做到这一点。

使用导航移动相同的url或页面不会重新装载页面并重置字段值。

更好的是,你实际上从你的行动创建者那里返回了一个承诺,并自己重置状态

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: ""})
});
}

相关内容

  • 没有找到相关文章

最新更新