反应路由器 Link 以有条件地渲染按钮

React router Link to conditionally render button

我有一个带有 onclick 的按钮,该按钮将其带到一个显示询问“您确定吗”的警报的功能。如果此人在警报上单击“确定”,我希望 link 转到某个页面。如果他们点击取消,我希望它转到不同的页面。这是我的...

        <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 为真,我想渲染“/calibrateAir”,否则为“/”。

不要使用 link 组件(因为在锚标记内嵌套按钮是 bad html writing),使用 react router history 来完成你想要的。例如,如果您使用的是功能组件,您可以这样做

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