當用戶單擊基于類的組件(名為 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
uj5u.com熱心網友回復:
你應該試試這個。在您的組件中導航功能無法回傳導航。還有其他以編程方式切換路由的方法。閱讀此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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/406291.html
標籤:
