[英]Unrouted React component not updating when Route changes
我的 React 應用程序有一個 Header 組件,它位於 Router 組件內,但當然沒有路由。 由於某種原因,當路由發生變化時,Header 沒有更新。 它甚至不檢查是否需要更新。 Header中有一個區域需要根據當前的url進行更改,所以這是一個問題。 我什至嘗試將當前的 url 作為道具傳遞,但它似乎甚至沒有注意到變化。 這是 App.js 渲染方法:
return (
<div style={s.appContainer}>
<Router>
<Header
user={this.state.user}
style={s.header}
dataLoaded={this.state.dataLoaded}
/>
<div style={s.content}>
<Route path='/app/v2/reports'>
<ReportContainer user={this.state.user}/>
</Route>
<Route path='/app/v2/groups'>
<CourseContainer user={this.state.user}/>
</Route>
<Route exact={true} path='/app/v2/people'>
<PeopleContainer/>
</Route>
<Route path='/app/v2/people/:email' component={UserDetailsContainer} />
<Route path='/app/v2/lessons/:lesson_id' component={LessonDetailsContainer} />
<Route exact={true} path='/app/v2/learning/library' component={LearnerLibraryContainer} />
<Route exact={true} path='/app/v2' component={DashboardContainer} />
</div>
</Router>
</div>
)
我無法分享大部分 header,但此方法是嘗試檢查 url 的部分:
inLearnerMode() {
const currentPath = window.location.href || '';
return currentPath.includes('learning')
}
嘗試使用withrouter HOC 封裝 Header 組件,然后您可以使用傳遞給組件的道具訪問當前位置,因此您的組件應如下所示:
...
import { withRouter } from 'react-router-dom';
...
class Header extends React.Component {
inLearnerMode() {
const { location } = this.props;
const currentPath = location.pathname || '';
return currentPath.includes('learning')
}
render() {
...
}
}
export default withRouter(Header)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.