【问题标题】:React router Link to conditionally render button反应路由器链接以有条件地渲染按钮
【发布时间】:2021-03-31 11:02:27
【问题描述】:

我有一个带有 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 为真,则基本上我想渲染“/calibrateAir”,否则为“/”。

【问题讨论】:

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


    【解决方案1】:

    不要使用链接组件(因为在锚标签内嵌套一个按钮是bad html writing),使用反应路由器历史来完成你想要的。例如,如果您使用的是功能组件,您可以这样做

    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' is not defined no-undef
    • 你导入了这个:import { useHistory } from "react-router-dom"; ?
    • 糟糕。我导入了,但现在它说对象不是 useHistory 行的函数
    • 你使用的是哪个版本的 react 路由器?
    • 对不起。我的导入中有错字。这正在工作。谢谢!
    猜你喜欢
    • 2019-04-25
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2018-07-26
    • 1970-01-01
    相关资源
    最近更新 更多