Redux 如何根据状态更改索引路由
假设我有以下主要的React应用程序,使用Redux 如何根据状态更改索引路由,redux,react-router,react-redux,Redux,React Router,React Redux,假设我有以下主要的React应用程序,使用React-redux和React-router(但还没有React-router-redux): 在我的商店中,我的状态是isLoggedIn,当isLoggedIn为true时,我想将IndexRoute的组件更改为ShowEntries,如果为false,则返回到LoginRequiredPage。我不确定如何实现这一点,但可以想出几种方法: 使用IndexRoute上的react reduxconnect方法将isLoggedIn映射到其组件
React-redux
和React-router
(但还没有React-router-redux
):
在我的商店中,我的状态是isLoggedIn
,当isLoggedIn
为true时,我想将IndexRoute
的组件更改为ShowEntries
,如果为false,则返回到LoginRequiredPage
。我不确定如何实现这一点,但可以想出几种方法:
IndexRoute
上的react reduxconnect
方法将isLoggedIn
映射到其组件
属性的新值Home
组件,将其连接到商店,根据isLoggedIn
切换其子组件,并将Home
作为新的IndexRoute
组件我希望当前视图在索引路由处于活动状态且isLoggedIn状态更改时更改。最简单的方法是声明一个组件,该组件将根据存储的特定属性值返回
ShowEntries
或LoginRequiredPage
:
<Provider store={store}>
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="/login" component={Login} />
<Route path="/entries" component={ShowEntries} />
</Route>
</Router>
</Provider>
及
@connect(状态=>({
isLoggedIn:…//我的答案是第二个选项。您不能简单地将路由
或路由器
连接到存储,因此您需要通过路由
的组件
道具提供连接的组件,或者使用先前创建的存储直接在路由器配置中执行一些重定向魔术。如果您想要在onEnter钩子中的异步调用中获取数据。我指的是每个组件的不同数据(例如使用异步连接或类似的方法)。您将如何解决这个问题?这是一个单独的主题。但请记住,一旦连接组件,它将被更新(呈现)每次通过connect更改道具中的状态属性。将分两个阶段:我们不知道用户是否登录(null),然后我们知道用户是否登录(true)或未登录(false)。设置新值并根据它们呈现此值和该值将是解决方案。
<Provider store={store}>
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="/login" component={Login} />
<Route path="/entries" component={ShowEntries} />
</Route>
</Router>
</Provider>
@connect(state => ({
isLoggedIn: ... // <- place the correct value here
}))
class Index extends Component {
render() {
const {
isLoggedIn
} = this.props;
if (isLoggedIn) {
return <ShowEntries />
} else {
return <LoginRequiredPage />
}
}
}