首页 > 解决方案 > 我正在尝试创建一个简单的搜索,单击搜索按钮时它应该重定向到新组件。但是重定向根本不起作用?

问题描述

在这种方法中,我正在改变状态

showAlert() {
    if(this.state.userInput) {
      this.setState(() => ({
        toMyList: true
      }))
  }

如果状态改变,在渲染方法中。我正在重定向到我的新组件

render() {


     const { toMyList } = this.state


      if (this.state.toMyList === true) {
        return <Redirect push to="/MyList" />;
      }
    }

我在单击按钮时调用 showalert() 方法。

<button class="btn-search" type="button" onClick={() => {this.showAlert()}}>
              Search
            </button>

我是否必须对 index.js 进行任何更改才能使反应路由器工作?我当前的 index.js 是:

ReactDOM.render(<App />, document.getElementById('root'));


serviceWorker.unregister();

标签: reactjsreact-native

解决方案


关于“MyList”的路由定义应该在您定义路由结构的地方。就像在 App.js 中或您定义它的其他地方一样:

 render (){
    return (
      <div>
         <Router>
           <div>
             <Switch>
              <Route path="/" exact component={IndexPage} />
              <Route path="/MyList" exact component={MyList}/>
             </Switch>
           </div>
         </Router>
      </div>
   )    
 }

推荐阅读