React router链接到有条件渲染按钮



我有一个带有onclick的按钮,它将把它带到一个显示警报询问";你确定吗;。如果这个人点击了警报上的ok,我希望链接能转到某个页面。如果他们单击"取消",我希望它转到另一个页面。这是我的。。。

<Link to="/calibrateAir" params={{ moisture: props.moisture }}>
<MyButton onClick={() => {calibrateAgain()}}>
Calibrate Again
</MyButton>
</Link>

以及函数。。。

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)
})
}
}

基本上我想呈现"/calibrateAir";如果alertwindow为true/&";。

不要使用链接组件(因为在锚标记中嵌套按钮是糟糕的html编写(,使用react路由器历史记录来完成您想要的。例如,如果你正在使用一个功能组件,你可以进行

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

最新更新