【问题标题】:Navigate does not redirecting to the specified path in reactjs导航不会重定向到reactjs中的指定路径
【发布时间】:2022-01-01 07:09:41
【问题描述】:

当用户单击基于类的组件(名为 Counter)中的指定按钮(在本例中名为 Navigate)时,我试图重定向到另一个路由器。我为此使用<Navigate />。它不会重定向到我指定重定向到的页面(主页的路径='/')。此外,我没有收到任何错误。有人,请告诉我使用<Navigate /> 的最佳方式。

供参考,代码为:

import React, {Component} from "react";
import {Navigate} from 'react-router-dom'

class Counter extends Component {
    constructor(props){
        super(props)

        this.state = {
           
        }

        this.navigate = this.navigate.bind(this)
    }
    
    navigate(e){
        return <Navigate to="/" />
    }

    render(){
        return (
            <div className='text-center'>
                <h1>Hello there, this is a counter app</h1>
                <button onClick={this.navigate} >Navigate</button>
            </div>
        )
    }
}

export default Counter

【问题讨论】:

    标签: reactjs redirect navigation


    【解决方案1】:

    你应该试试这个。在您的组件中导航功能无法返回导航。还有其他以编程方式切换路由的方法。阅读此https://reactrouter.com/docs/en/v6/getting-started/concepts

    import React, {Component} from "react";
    import {Navigate} from 'react-router-dom'
    
    class Counter extends Component {
        constructor(props){
            super(props)
    
            this.state = {
               dashboard: false,
            }
    
            this.navigate = this.navigate.bind(this)
        }
        
        navigate(e){
            this.setState({dashboard:true})
        }
    
        render(){
            return (
                <div className='text-center'>
                    {this.state.dashboard && (
                        <Navigate to="/dashboard" replace={true} />
                    )}
                    <h1>Hello there, this is a counter app {this.state.dashboard && <span>dashboard</span>}</h1>
                    <button onClick={this.navigate} >Navigate</button>
                </div>
            )
        }
    }
    
    export default Counter
    

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 2020-08-17
      • 2014-12-31
      • 2015-04-14
      • 2020-12-19
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多