我有一个表单,提交后会在我的 MongoDB 数据库中创建一个新条目。
不过,在执行此操作后,我希望这个新条目显示在我的“重定向”页面上。但是 - 它不是“刷新”页面,而是简单地重定向,并且页面看起来与上次导航离开时相同。
所以我的问题是,如何重构我的代码,以便在提交表单时重定向也刷新重定向页面?
这是我的提交代码:
onSubmit = (e) => {
e.preventDefault();
axios.post("/api/submitDebt", {
creditCard: this.state.creditCardToggled,
personalLoan: this.state.personalLoanToggled,
provider: this.state.provider,
balance: this.state.balance,
limit: this.state.limit,
monthly: this.state.monthly,
interest: this.state.interest,
borrowed: this.state.borrowed
})
this.props.history.push('/dashboard');
}
我假设这是因为它是“this.props.history”,所以它返回原始页面。重构此重定向以在提交表单时重新加载页面的最佳方法是什么?
如有任何帮助,我们将不胜感激。谢谢!
编辑:呈现表单提交的仪表板组件。我在移动设备上执行此操作,希望一切顺利!
class IndividualDebts extends Component {
constructor(props) {
super(props)
this.state = {
debts: []
}
}
componentDidMount() {
axios.get("/api/fetchDebtCards")
.then((response) => {
this.setState({ debts: response.data })
})
.catch(e => {
console.log(e)
})
}
render() {
const fetchDebts = this.state.debts.map (debt => {
return (
<IndividualDebtCard key={debt._id}
picture={(`../images/${debt.provider}.jpg`)}
provider={debt.provider}
type={debt.creditCard === 'true' ? "Credit Card" : "Personal Loan" }
balance={debt.balance}
limit={debt.creditCard === 'true' ? debt.limit : debt.borrowed}
monthly={debt.monthly}
interest={debt.interest} />
)
})
return (
<div>
<section className="individual-debts-section">
<div className="individual-debts-container">
{this.state.debts.length === 0 ?
<div className="no-debts-container">
<h3>There are no debts linked yet. Why not try adding one now?</h3>
<ActionButton link="link-debt" type="button" text="Link debt" />
</div> : <div className="individual-debts-card-container">{fetchDebts}</div> }
</div>
</section>
</div>
)
}
}
export default IndividualDebts;
另一个编辑:为 Dashboard 组件添加了带有 React Router 的路由。
<Route path="/dashboard" component={Dashboard} />
最佳答案
我觉得问题是您在导航到仪表板之前没有等待 axios 调用(异步)完成。也许尝试使用 async/await 之类的东西:
onSubmit = async (e) => {
e.preventDefault();
await axios.post("/api/submitDebt", {
creditCard: this.state.creditCardToggled,
personalLoan: this.state.personalLoanToggled,
provider: this.state.provider,
balance: this.state.balance,
limit: this.state.limit,
monthly: this.state.monthly,
interest: this.state.interest,
borrowed: this.state.borrowed
})
this.props.history.push('/dashboard');
}
或者,您可以像这样使用 then/catch block :
onSubmit = (e) => {
e.preventDefault();
await axios.post("/api/submitDebt", {
creditCard: this.state.creditCardToggled,
personalLoan: this.state.personalLoanToggled,
provider: this.state.provider,
balance: this.state.balance,
limit: this.state.limit,
monthly: this.state.monthly,
interest: this.state.interest,
borrowed: this.state.borrowed
})
.then(()=> this.props.history.push('/dashboard'))
.catch(()=> console.log("error in posting data"));
}
关于reactjs - 在 React 前端提交表单时重定向和刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64410703/