导航不会重定向到 reactjs 中的指定路径
Navigate does not redirecting to the specified path in reactjs
当用户在基于 class 的组件(名为 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
你应该试试这个。在您的组件中导航功能不能 return 导航。还有其他以编程方式切换路由的方法。阅读此 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
当用户在基于 class 的组件(名为 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
你应该试试这个。在您的组件中导航功能不能 return 导航。还有其他以编程方式切换路由的方法。阅读此 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