Warm tip: This article is reproduced from serverfault.com, please click

reactjs- React 路由器链接到有条件的渲染按钮

(reactjs - React router Link to conditionally render button)

发布于 2020-12-21 16:59:14

我有一个带有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”,否则为“ /”。

Questioner
Justin Oberle
Viewed
0
jean182 2020-12-22 01:24:59

不要使用链接组件,请使用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>
 );
 }