【问题标题】:React Redux: Different actions for list itemsReact Redux:列表项的不同操作
【发布时间】:2020-09-26 20:43:55
【问题描述】:

我有一个由 React 组件组成的列表:

        <div className="card-list">
            {cards.map((card, i) => (
                <Card card={card} key={card.cardId} index={i}/>
            ))}
        </div>

问题是点击一张卡片应该为被点击的卡片打开一个模式窗口。要调用模态窗口,我在 Card 组件中使用以下代码:

    const Card = ({card, key, index}) => {
        const dispatch = useDispatch();
        const showModal = useSelector(state => state.modal.showContentModal);

        return (
            <div>
                //this is card view
                <div onClick={() => dispatch(showContentModal())}>    
                    <h3>{card.name}</h3>
                </div>

                //this is modal window
                <div id={`modal-overlay-container-${key}`} className={`modal-overlay ${showModal && "active"}`}>
                    <div id={`modal-div-${key}`} className={`modal ${showModal && "active"}`}>
                        <p className="close-modal" onClick={() => dispatch(hideContentModal())}>
                            <svg viewBox="0 0 20 20">
                                <path fill="#8e54e9" d="..."/>
                            </svg>
                        </p>
                        <div className="modal-content">
                        <CardContent card={card} index={index}/>
                    </div>
                    </div>
                </div>
            </div>
        )
  }

  export default Card;

showСontentModal() 动作改变了布尔标志,这使得模态窗口active,而hideModalContent() 则相反。但是由于列表中的所有组件都链接到一个操作,因此单击任何卡都会为所有组件打开一个模式窗口。有没有办法只针对特定卡触发动作?

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    我看到有两种方法可以解决这个问题。

    1. 在卡片组件中使用本地状态而不是 redux 状态
    2. state.modal.showContentModal 中使用卡 ID 而不是布尔值

    如果您在其他组件中不需要state.modal.showContentModal,那么我更喜欢第一个选项。

    const [showModal, setShowModal] = useState(false)
    
    const handleOpenModal = () => setShowModal(true)
    
      <div onClick={handleOpenModal}>    
        <h3>{card.name}</h3>
      </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-25
      • 2020-09-23
      • 2021-10-05
      • 2017-08-15
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多