我有一个带有onclick的按钮,它将其带到显示警告“你确定”的警报的功能。如果该人在警报上单击“确定”,则我希望链接转到某个页面。如果他们单击“取消”,我希望它转到另一个页面。这是我所拥有的...
<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)
})
}
}
基本上,如果alertwindow为true,则我想呈现“ / calibrateAir”,否则为“ /”。
不要使用链接组件,请使用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>
);
}
我收到此错误“ useHistory”未定义no-undef
您是否导入了此内容:从“ react-router-dom”中导入{useHistory};?
哎呀 我导入了,但现在它说对象不是useHistory行的函数
您正在使用哪个版本的React Router?
我很抱歉。我的输入中有错字。现在正在工作。谢谢!