[英]React-Router: Programatically routing to a route from the root element
I am trying to route my application so that when it is any route, say /
or /listing/foo
, I can use the navbar's textbox to search to navigate to /search/${search-term}
.我正在尝试路由我的应用程序,以便当它是任何路由时,例如
/
或/listing/foo
,我可以使用导航栏的文本框进行搜索以导航到/search/${search-term}
。 However, the conventional methods for programmatically routing use history.push
which isn't available in the root element, since the navbar
is technically outside the Switch
element.然而,以编程方式路由的传统方法使用在根元素中不可用的
history.push
,因为navbar
在技术上位于Switch
元素之外。
Here's the example code:这是示例代码:
import {
HashRouter as Router,
Switch,
Route,
NavLink as Link,
Redirect
} from 'react-router-dom';
import React from 'react';
class App extends React.Component{
constructor(){
this.state = {
searchTerm: '',
}
}
render(){
return(
<>
<nav>
<input className="input" type="text" placeholder="Search listings..." onChange={e => this.startSearching(e)} value={this.state.searchTerm}/>
</nav>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/search/:searchTerm' component={Search} />
</Switch>
</>
)
}
startSearching(){
this.setState({
searchTerm: e.target.value
});
// Omitted debouncing methods
return (<Redirect push to=`/search/${this.state.searchTerm}` />); // Doesn't work
this.props.history.push(`/search/${this.state.searchTerm}`) // this.props is undefined
}
}
What should I do to switch the page inside the <Switch>
?我应该怎么做才能在
<Switch>
内切换页面?
You can wrap your nav component with the withRouter so in your component you can use the history.push
您可以使用 withRouter 包装您的导航组件,以便在您的组件中使用
history.push
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
// A simple component that shows the pathname of the current location
class Navbar extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
render() {
const { match, location, history } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const NavbarWithRouter = withRouter(Navbar);
see more detail at https://reactrouter.com/web/api/withRouter在https://reactrouter.com/web/api/withRouter上查看更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.