考虑以下 React Router 设置:
<Router history={history}>
<Route path="/" component={Root}>
<Route path="/users" component={UserList}/>
<Route path="/users/new" component={UserCreate}/>
<Route path="/users/:id" component={User}/>
<Route path="/tags" component={TagList}/>
<Route path="/tags/new" component={TagCreate}/>
<Route path="/tags/:id" component={Tag}/>
</Route>
</Router>
在任何时候,我都希望能够显示特定的模式。现在,我正在使用 modal
来管理它我的 Redux 商店中的属性(property)。 Root
组件 ( <Route path="/" component={Root}>
) 检查此属性并在设置时呈现必要的模态。
这可以通过 React Router 实现吗?所以不必保留 modal
我的 redux 商店中的属性,我可以导航到类似 /users#modal
的东西或 /users/modal
并获得 UserList
呈现的组件(如 <Route path="/users" component={UserList}/>
中定义)和模态组件
最佳答案
您可以执行此操作的一种方法是在您的各个组件的 componentDidMount 中检查您的位置哈希。
componentDidMount() {
if (window.location.hash) {
const hash = window.location.hash.substring(1);
if (hash === "modal") {
//show your modal here.
}
}
}
如果所有组件都需要以这种方式运行,您可以让所有组件继承自一个公共(public)基类。
关于javascript - 支持在任何路由上显示模态的 React Router 路由配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42095638/