【问题标题】:Update global state in targeted component without rerendering components that share global state更新目标组件中的全局状态,而不重新渲染共享全局状态的组件
【发布时间】:2020-11-09 21:30:17
【问题描述】:

我正在尝试通过跟踪全局 z-index 来增加组件 onClick 的 z-index,只要单击共享全局 z-index 状态的组件之一,该全局 z-index 就会增加。这本质上是为了确保单击的任何组件都具有最高的 z-index。

但是,我无法弄清楚如何防止所有组件更新 z-index,因为它们都通过 props 订阅了此状态。我将 Redux 和 mapStateToProps 与 mapDispatchToProps 一起用于点击处理程序。

我试过这样的减速器:

case "INC_Z_COMP1":
    return {
        ...state,
        zGlobal: ++state.zIndex.global,
        zComponent1: state.zIndex.global,
    }
case "INC_Z_COMP2":
    return {
        ...state,
        zGlobal: ++state.zIndex.global,
        zComponent2: state.zIndex.global,
    }

...为了给每个组件自己的 z 索引状态,它只是镜像全局状态,但这只是保持 z 索引为零。我尝试了一些类似的东西,但没有奏效。我不确定我是否会以错误的方式解决这个问题,或者在本地更新反映全局状态的状态的最佳方式是什么,但我们将不胜感激。

【问题讨论】:

  • 为每个组件保留单独的 z-index 并让 reducer 找出下一个 z-index 不是更好吗?
  • 这就是我正在尝试的,但我试图使用全局 z-index 来设置各个 z-index,正如您在代码中看到的那样。每个组件在状态下都有自己的 z-index 值,但我试图将全局值镜像到目标组件 onclick。你到底是什么意思?

标签: javascript reactjs redux


【解决方案1】:

您可以创建一个函数getNextZ,给定一个具有所有每个组件 z-index 的对象返回下一个 z-index。然后,您将使用该函数来计算下一个 z-index 并更新存储。每个组件应该只知道自己的 z-index。

case "INC_Z_COMP1":
return {
    ...state,
    zIndexes: { ...state.zIndexes, Component1: getNextZ (state.zIndexes) },
}

case "INC_Z_COMP2":
return {
    ...state,
    zIndexes: { ...state.zIndexes, Component2: getNextZ (state.zIndexes) },
}

如果您直接将 z-index 存储为值:

{ // ...state
  zIndexes: {
    Component1: 1,
    Component2: 2,
    Component3: 7,
  }
}

那么你的函数可能是这样的;

const getNextZ = zIndexes => Math.max (...Object.values (zIndexes)) + 1;

【讨论】:

  • 这就像一个魅力。非常感谢您提供了一个非常好的解决方案。
【解决方案2】:

您为什么不保留对您状态中最后一次单击的组件的引用。那么reducer会是

case "COMPONENT_CLICKED":
    return {
        ...state,
        lastClikedComponent: action.clickedComponent,
    }

并在每个组件中检查 currentcomponent === action.clickedComponent 然后 zindex = 2147483647 否则 zindex = 0

currentcomponent 应该是一个唯一的 id,与你在 react 中用于 key in loop 的类型相同

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 2018-06-05
  • 2023-03-09
  • 2019-10-06
  • 2019-11-09
  • 1970-01-01
相关资源
最近更新 更多