反应模式自定义组件未显示正确的数据

时间:2020-01-08 13:27:43

标签: javascript reactjs react-hooks

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

//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>
主组件中的

每次都会显示预期的属性,但是Modal总是显示数组中的最后一个home_team项目(例如Pretoria U)

1 个答案:

答案 0 :(得分:1)

您需要在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>
);