【问题标题】:Redirect doesn't work after onClick in React在 React 中的 onClick 后重定向不起作用
【发布时间】:2021-10-14 09:12:13
【问题描述】:

我对来自react-router-dom<Redirect /> 有疑问。它不会将用户重定向到给定的路径。

    const getCourse = () => {
            console.log('gg');
            <Redirect to={"/courses/" + id} /> //
        }
...
    <div className="menu__course" onClick={() => getCourse()}>

在控制台中我看到 'gg' 所以调用了函数但我的路径没有改变

【问题讨论】:

    标签: reactjs redirect react-router


    【解决方案1】:

    &lt;Redirect /&gt; 需要由外部函数返回(即:react 组件)

    相反,您的 getCourse 回调应该 setButtonClicked(true) 并且您应该执行以下操作:

    if (buttonClicked) {
        return <Redirect to... />
    }
    

    【讨论】:

      【解决方案2】:

      重定向组件在挂载到虚拟 dom 时工作。 您不能从函数中调用它。以下问答深入探讨了如何解决您的问题

      Programmatically navigate using react router V4

      【讨论】:

        【解决方案3】:

        你可以参考这样的东西

                const [course, setCourse] = useState()     
        
                const getCourse = () => {
                    console.log('gg');
                    setCourse("gg")
                }
        
                if(course === "gg") return <Redirect to={"/courses/" + id} />
        
        
        
        
            return <div className="menu__course" onClick={() => getCourse()}>
        

        或者如果您希望从 func 本身重定向,请使用

                const getCourse = () => {
                    console.log('gg');
                    history.push(your-route)
                }
        

        【讨论】:

          猜你喜欢
          • 2017-10-05
          • 1970-01-01
          • 2018-05-21
          • 2021-11-04
          • 2014-10-06
          • 1970-01-01
          • 2016-01-10
          • 1970-01-01
          • 2021-07-24
          相关资源
          最近更新 更多