React + Redux + Router - 我应该为所有页面/组件使用一种状态/存储吗? [英] React + Redux + Router - should I use one state/store for all pages/components?

查看:27
本文介绍了React + Redux + Router - 我应该为所有页面/组件使用一种状态/存储吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React + Redux,在阅读了关于 react-router-reduxredux-router,并在阅读 Dan Abramov 的回答,我决定使用香草"反应路由器(在这一点上,我不关心时间旅行等).

I am using React + Redux, and after reading about react-router-redux and redux-router, and after reading Dan Abramov's answer, I decided to use "vanilla" react-router (I don't care about time travel etc. at this point).

剩下的唯一悬而未决的问题是如何处理不同路由的状态.在我的应用程序中,每个路由子树都可以是不同的独立部分(尤其是当它变大时).让一家商店处理所有路线/页面仍然是一种好习惯吗?我不应该(至少)为每个主要路线路径设置不同的商店/状态吗?

The only open question left is how to handle state across different routes. Each route sub-tree can be a different and independent section in my application (especially when it become bigger). Is it still a good practice to have one store to handle all routes/ pages? Shouldn't I (at least) have a different store/state for each main route path?

我认为路由应该是某种无状态和独立的,这意味着如果我直接转到我的一个链接,它应该可以工作,并且不会知道其他兄弟路由.我应该将其反映到我的商店吗?

I think routes should be some kind of stateless and independent, meaning that if I go directly to one of my links, it should work, and won't be aware of other sibling routes. Should I reflect it to my store?

编辑

经过更多思考,我想使用不同的 reducer + "CombineReducers" 可以解决问题.我唯一需要验证的是,导航时以前的路线状态不会持续

After some more thinking, I guess that using different reducers + "CombineReducers" will do the trick. The only thing left to for me to verify is that state of former routes does not persist while navigating

推荐答案

验证以前路由的状态不会持续存在的可能解决方案:

On of the possible solutions to verify that state of former routes does not persist:

当用户在页面之间导航时,每个路由中的顶级组件都会安装和卸载.你可以使用他们的生命周期方法发送任何 redux 事件来清理你的状态.

Top level components in each route are mounting and unmounting when user navigates between pages. You can use their lifecycle methods to send any redux events to clean your state.

例如从 componentWillUnmount 发送 CLEAN_STATE.您应该在顶级减速器端捕获此事件,并从中返回初始状态.为此,您可以使用 undefined 作为状态参数手动调用所有嵌套的 reducer.在这种情况下,每个 reducer 都会返回它的初始状态.

For example send CLEAN_STATE from componentWillUnmount. You should catch this event in your top level reducer end return initial state from it. To do it you can manually call all nested reducers with undefined as a state parameter. In that case each reducer will return it's initial state.

这篇关于React + Redux + Router - 我应该为所有页面/组件使用一种状态/存储吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆