使用材料搜索栏导航到另一个页面



我正在应用程序的标题中使用材料搜索栏,并尝试导航到本地主机上请求搜索的页面"/search"。搜索栏本身的代码很简单:

 <SearchBar
   onChange = {() => console.log('onChange')}
   onRequestSearch = {() => this.setRedirect()}
   style = {{ margin: '0 auto', maxWidth:800}}/>

现在,我尝试以多种方式实现 setRedirect 函数,但没有运气。首先,我简单地尝试了:

setRedirect() {
  this.props.history.push('/search');
}

但这给出了一个错误 未定义不是对象 (评估 this.props.history(。我确实在我的主应用程序中为"/search"页面设置了路线。我也尝试使用重定向:

constructor(props) {
  super(props);
  this.state = {
     redirect = false
    }
}
setRedirect()  {
  this.setState({
    redirect: true  
  }
}

在渲染方法中:

render() {
  if(this.state.redirect)  {
    return (
        <Router>
          <div>
            <Redirect push to="/search"/>
            <Route path="/search" exact strict component={Search}/>
          </div>
        </Router>
    );
   }
  else {
   // return other stuff
 }
}      

这只会导致当我在搜索栏中键入内容并按回车键时整个页面变为空白。浏览器中的地址也不会更改为"/search"。不知道我做错了什么。只需尝试在用户在搜索栏中输入文本并按回车键后导航到另一个页面。任何建议将不胜感激。提前谢谢你!

尝试添加 withRouter HoC,然后使用 this.props.history.push(( 重试

import {  withRouter } from 'react-router-dom'
...
export default withRouter(MyComponent);

相关内容

最新更新