在这种方法下,我正在更改状态
showAlert() {
if(this.state.userInput) {
this.setState(() => ({
toMyList: true
}))
}
如果状态已更改,则在render方法中。我将重定向到我的新组件
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中进行任何更改以使React Router工作吗? 我当前的index.js是:
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
答案 0 :(得分:0)
关于“ MyList”的路由定义应该在定义路由结构的位置。就像在App.js或您定义它的其他地方一样:
render (){
return (
<div>
<Router>
<div>
<Switch>
<Route path="/" exact component={IndexPage} />
<Route path="/MyList" exact component={MyList}/>
</Switch>
</div>
</Router>
</div>
)
}