简体   繁体   English

React / redux + bootstrap,使模态显示对于组件是唯一的

[英]React/redux + bootstrap, make modal show unique for component

I have a component that shows a modal to pop up some content in my map. 我有一个组件,显示一个模式来弹出我的地图中的一些内容。 I have a pretty straight forward set up : 我有一个很直接的设置:

The JSX looks like this : JSX看起来像这样:

  <Modal show={this.props.results.showPreviewModal} >
         {myPreviewContent}
  </Modal>

2 action-creators to open, close, and set the current item : 2个动作创建者来打开,关闭和设置当前项目:

export function previewAsset(result) {
    return {
        currentResult: result,
        type: actions.PREVIEW_ASSET
    };
}

export function closePreviewModal() {
    return {
         type: actions.CLOSE_PREVIEW_MODAL
    };
}

And their reducers : 他们的减速器:

case actions.PREVIEW_ASSET:
      return state.set('currentPreview', action.currentResult).set('showPreviewModal', true);

case actions.CLOSE_PREVIEW_MODAL:
      return state.set('showPreviewModal', false);

Now, this seems to work fine. 现在,这似乎工作正常。 However, the issue is that the component that has the modal inside of it is inside a map, as it is a singular search result (each result component has a some functionality so it is it's own component that is mapped over with results). 但是,问题在于其中包含模态的组件位于地图内部,因为它是一个单一的搜索结果(每个结果组件都有一些功能,因此它是自己的组件,与结果一起映射)。 The issue is that if I have 10 results, this modal opens 10 times when I click the button that fires the previewAsset action. 问题是如果我有10个结果,当我点击触发previewAsset动作的按钮时,这个模态会打开10次。

This makes sense, because the showPreviewModal is accessible by all components, but what I am wondering is if there is a way to make then unique for each component individually, so only the 1 modal opens, not all 10. Unsure how to approach this within react/redux, would very much appreciate any advice, thanks! 这是有道理的,因为所有组件都可以访问showPreviewModal ,但我想知道的是,是否有一种方法可以单独为每个组件制作唯一的,所以只打开1个模态,而不是全部10.不确定如何在react / redux,非常感谢任何建议,谢谢!

An approach I've used successfully is to pull the Modal component out of the loop (or map() in this case), and have a reducer for currentItem or something similar, which gets set when an item is selected (you could also use currentItemIndex , and then select the current item based on that in your connect() call). 我成功使用的一种方法是将Modal组件拉出循环(或者在这种情况下为map() ),并为currentItem或类似的东西提供一个reducer,当选择一个项目时它会被设置(你也可以使用) currentItemIndex ,然后根据connect()调用中的项选择当前项。

In the parent component, you'd have the Modal as a child, and only display it if that currentItem is not null. 在父组件中,您将Modal作为子项,并且只有在currentItem不为null时才显示它。

Here's a quick JSBin example to show you what I mean: 这是一个快速的JSBin示例,向您展示我的意思:

http://jsbin.com/fefoxoy/edit?html,js,console,output http://jsbin.com/fefoxoy/edit?html,js,console,output

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

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