我使用React路由器显示相同的组件,但在每条路由上都有不同的支持:
<BrowserRouter>
<div>
<Route exact path="/" render={() => LOGGED_IN ? <Redirect to="/profile" /> : <Login />} />
<Route path="/profile/:id" render={(props) => <App {...props} page="profile" pageLadder={['Home', 'Profile']} />}/>
<Route path="/team" render={() => <App page="team" pageLadder={['Home', 'Team']} />}/>
<Route path="/transactions" render={() => <App page="transactions" pageLadder={['Home', 'Transactions']} />}/>
<Route path="/tournaments" render={() => <App page="tournaments" pageLadder={['Home', 'Tournaments']} />}/>
<Route path="/tournament/:id" render={(props) => <App {...props} page="tournament" pageLadder={['Home', 'Tournament', props.match.params.id]} />}/>
<Route path="/match/:id" render={(props) => <App {...props} page="match" pageLadder={['Home', 'Match', props.match.params.id]} />} />
<Route path="/scrims" render={() => <App page="scrims" pageLadder={['Home', 'Scrims']} />} />
<Route path="/faq" render={() => <App page="faq" pageLadder={['Home', 'FAQ']} />} />
<Route path="/staff" render={() => <App page="staff" pageLadder={['Home', 'Staff']} />} />
<Route path="/privacy" render={() => <App page="privacy" pageLadder={['Home', 'Privacy Policy']} />} />
<Route path="/tos" render={() => <App page="tos" pageLadder={['Home', 'Terms of Service']} />} />
</div>
</BrowserRouter>我还需要捕获404个错误,所以我添加了Switch和<Route component={NotFound} />
<BrowserRouter>
<Switch>
<Route exact path="/" render={() => LOGGED_IN ? <Redirect to="/profile" /> : <Login />} />
... more routes
<Route component={NotFound} />
</Switch>
</BrowserRouter>404确实可以工作,但是每个<Link>元素都会停止工作--单击之后,url确实会改变,但是组件保持不变,除非我刷新站点。
我尝试将我的代码更改为这个来测试:
<BrowserRouter>
<Switch>
<Route path="/team" component={Login} />
<Route path="/profile/" component={App} />
</Switch>
</BrowserRouter>使用此代码,<Link>组件确实按预期工作。
我能做些什么来使我的第一段代码正常工作呢?
发布于 2018-06-06 14:26:48
从您的代码示例中:
class App extends Component {
constructor(props){
super(props);
// appStore is an instance of react-easy-state library
// App component puts the components together, the actual pages are in AppMain component (look below for code)
appStore.changePage(this.props.page, this.props.pageLadder, this.props.match ? this.props.match.params.id : -1);
// this function changes appStore.page.name value and it's a global type store
}
render() {
return (
<div>
<div>
<Sidebar />
<AppMain />
</div>
</div>
);
}
}您正在构造函数中调用,该构造函数只在组件首次初始化时被调用一次。即使您在几个路由上都有组件,但是当您更改路由和道具时,它不会被卸载,这意味着构造函数再也不会被调用了。
您需要做的是,当您的componentDidUpdate支持更改时,使用更改页面:
componentDidUpdate (prevProps, prevState) {
if(prevProps.page !== this.props.page) {
appStore.changePage(this.props.page, this.props.pageLadder, this.props.match ? this.props.match.params.id : -1);
}
}现在,您将比较当前道具中的prevProps,如果page支柱发生了更改,则需要再次触发appStore.changePage。现在,我不知道appStore.changePage在做什么,所以我不确定您是否也需要更新<AppMain />,但是这应该会使您走上正确的轨道。
https://stackoverflow.com/questions/50722553
复制相似问题