简体   繁体   English

React:如何将组件身份传递给Redux状态

[英]React: how to pass component identity to Redux state

Is it safe to pass this to Redux action creator from withing component defined using React.createClass ? this与使用React.createClass定义的组件一起传递给Redux动作创建者是否安全?

I have defined the following reducer: 我定义了以下减速器:

const unsavedChangesProtectionReducer = handleActions({
    [ENABLE_UNSAVED_CHANGES_PROTECTION]: (unsavedChangesProtection, action) => ({protected: true}),
    [DISABLE_UNSAVED_CHANGES_PROTECTION]: (unsavedChangesProtection, action) => ({protected: false})},
    {protected: false}
)

Multiple components may set/unset the global state.unsavedChangesProtection.protected flag, and problem arises from unsetting this flag, as component shouldn't unset it if some other component has set it before this component. 多个组件可能会设置/取消设置全局state.unsavedChangesProtection.protected标志,并且由于取消设置此标志而引起问题,因为如果某个其他组件在此组件之前设置了该标志,则该组件不应取消设置它。

One solution is to check if flag is already set and if not, set it, store the info about component setting the flag in component's internal state, and unset it if internal state states that component has set the flag. 一种解决方案是检查标志是否已设置,如果没有设置,则将其设置,将有关设置标志的组件的信息存储在组件的内部状态,如果内部状态表明该组件已设置了标志,则将其取消设置。 However, this violates the DRY principle, as I have to introduce exactly same login in every component. 但是,这违反了DRY原则,因为我必须在每个组件中引入完全相同的登录名。

More generalized solution would be to store the identity of the component which lastly mutated the global state as a member of state itself, so each component can see from the state if it's their change and unset in accordingly. 更通用的解决方案是存储最后将全局状态突变为状态本身的成员的组件身份,以便每个组件都可以从状态中查看其是否已更改并相应地未设置。 Is this possible to implement in React, as each component are re-initialized when mounted/unmounted 这可能在React中实现吗,因为每个组件在安装/卸载时都会重新初始化

当然,在reducer中具有setBy属性是可行的,并且您还必须为每个组件添加额外的逻辑到componentWillUnmount方法,如果该组件负责设置/ setBy设置,则该组件可能会改变将触发reset setBy操作的标志首先是标志(您不想保留从dom中删除的组件的引用,因为它将阻止所有其他组件更改标志)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM