反应路由器链接以有条件地呈现按钮

时间:2020-12-21 16:59:14

标签: reactjs react-router onclick alert conditional-rendering

我有一个带有 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)
        })
    }
}

基本上我想渲染“/calibrateAir”,如果alertwindow为真,否则为“/”。

1 个答案:

答案 0 :(得分:1)

不要使用链接组件,使用反应路由器历史来完成你想要的。例如,如果您使用的是功能组件,您可以这样做

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>
 );
 }
相关问题