首页 > 解决方案 > 反应模态自定义组件未显示正确数据

问题描述

我已经使用反应钩子构建了这个模态组件。但是,模式弹出时显示的数据不正确(它始终显示数组中最后一个元素的名称属性)。

//Modal.js
import ReactDOM from 'react-dom';

const Modal = ({ isShowing, hide, home_team }) => {return isShowing ? ReactDOM.createPortal(
  <React.Fragment>
    <div className="modal-overlay"/>
    <div className="modal-wrapper">
      <div className="modal">
        <div className="modal-header">
        <a>Home team: {home_team}</a>
          <button type="button" className="modal-close-button" onClick={hide}>
          </button>
        </div>
      </div>
    </div>
  </React.Fragment>, document.body
) : null;}

export default Modal;

// 主要组件

const League = ({ league, matches }) =>{ 
    const {isShowing, toggle} = useModal(); 
    return (
    <Fragment>
        <h2>{league}</h2>
        {
            matches.map((
                { 
                    match_id,
                    country_id,
                    home_team
                }
            ) => 
            {
                return (
                    <div>
                        <p>{match_id}</p>
                        <button className="button-default" onClick={toggle}>Show Modal</button>
                        <a>{home_team}</a>
                        <Modal
                            isShowing={isShowing}
                            hide={toggle}
                            home_team={home_team}
                        />
                        <p>{home_team}</p>
                    </div>
                )
            })
        }
    </Fragment>
  )};

这是匹配数据集的样子:

 [{
    match_id: "269568",
    country_id:"22",
    home_team: "Real Kings"
},
{
    match_id: "269569",
    country_id:"22",
    home_team: "Steenberg United"
},
{
    match_id: "269570",
    country_id:"22",
    home_team: "JDR Stars "
},
{
    match_id: "269571",
    country_id:"22",
    home_team: "Pretoria U"
},
]

我不确定发生了什么,因为数据似乎可以正常传递。

<p>{home_team}</p>

在主组件中每次都显示预期的属性,但是模态总是显示home_team数组中的最后一项(例如比勒陀利亚 U)

标签: javascriptreactjsreact-hooks

解决方案


您需要在 map 函数中调用 useModal 。否则,您将在切换所有模态时打开,最后一个与其他模态重叠


const HomeTeam = ({ match_id, country_id, home_team }) => {
  const {isShowing, toggle} = useModal();

  return (
    <div>
       <p>{match_id}</p>
       <button className="button-default" onClick={toggle}>Show Modal</button>
       <a>{home_team}</a>
       <Modal
         isShowing={isShowing}
         hide={toggle}
         home_team={home_team}
       />
       <p>{home_team}</p>
     </div>
   )
}

const League = ({ league, matches }) => (
  <Fragment>
    <h2>{league}</h2>
    { matches.map((match) => <Hometeam {...match} /> }
  </Fragment>
);


推荐阅读