[英]React router Link to conditionally render button
我有一個帶有 onclick 的按鈕,它將它帶到 function 顯示一個警告,詢問“你確定”。 如果此人在警報上單擊“確定”,我希望將 go 鏈接到某個頁面。 如果他們點擊取消,我想把它到 go 到不同的頁面。 這是我所擁有的...
<Link to="/calibrateAir" params={{ moisture: props.moisture }}>
<MyButton onClick={() => {calibrateAgain()}}>
Calibrate Again
</MyButton>
</Link>
和 function...
function calibrateAgain() {
const user = localStorage.getItem('user')
const alertWindow = window.confirm("Are you sure you want to calibrate?")
if (alertWindow) {
axios.post("http://localhost:3001/api/calibrate",
{airValue: null, waterValue: null, user: user}).then((response) => {
alert(response.data)
}, (error) => {
console.log(error)
})
}
}
基本上,如果 alertwindow 為真,則我想渲染“/calibrateAir”,否則為“/”。
不要使用鏈接組件,使用反應路由器歷史來完成你想要的。 例如,如果您使用的是功能組件,您可以這樣做
import React from "react";
import { useHistory } from "react-router-dom";
export default function YourComponent() {
const history = useHistory()
function calibrateAgain() {
const user = localStorage.getItem('user')
const alertWindow = window.confirm("Are you sure you want to calibrate?")
if (alertWindow) {
axios.post("http://localhost:3001/api/calibrate",
{airValue: null, waterValue: null, user: user}).then((response) => {
// Push to the calibrateAir if response succeeds
history.push("/calibrateAir");
alert(response.data)
}, (error) => {
// Push to the / if response fails
history.push("/");
console.log(error)
})
} else {
// Push to the / if user press cancel in the alert
history.push("/");
}
}
return (
<MyButton onClick={calibrateAgain}>
Calibrate Again
</MyButton>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.