对功能组件做出反应避免重新渲染

时间:2020-06-29 14:53:47

标签: reactjs

我正在使用Hooks,如何避免重新渲染?我问这个问题的目的是,我正在使用div从div高度溢出的项目使用滚动,当我使用onMouseOver专注于某个项目时,我的功能组件正在渲染自身,并且滚动返回了初始位置。因此,我不删除div的最后一项。您有什么建议可以避免重新渲染吗?

我的组件:

 import React from 'react'

  type removeDisplayItem = {
    dataId: number;
    display: boolean
}

  const PlayerCalendar = () => {
  const [removeDisplayData, setRemoveDisplayData] = useState<removeDisplayItem>({ dataId: -1, display: false })

    const handleRemove = (dataId: number, display: boolean) => {

        const removeData = {
            dataId: dataId,
            display: display
        }
       
        setRemoveDisplayData(removeData)
    }

    const renderScheduleContentCell = (data: scheduleItem) => {
      
        return (
            <>
                <div className="cell-content-wrapper" style={removeDisplayData.dataId === data.id && removeDisplayData.display === true ? { display: "none" } : { display: "flex" }}
                    onMouseOver={() => handleDisplayRemove(data.id, true)}>

                    <div className="start-time-text">{moment(data.startTime).format("HH:mm")}</div>
                    <div className="dash"> - </div>
                    <div className="end-time-text"> {moment(data.endTime).format("HH:mm")} </div>

                </div>

                <div className="cell-content-wrapper" onMouseLeave={() => handleDisplayRemove(data.id, false)}
                    style={removeDisplayData.dataId === -1 ? { display: "none" } : removeDisplayData.dataId === data.id && removeDisplayData.display === true ? { display: "flex", justifyContent: "space-between", backgroundColor: "#8c9296", color: "white", cursor: "pointer" } : { display: "none" }}
                    onClick={() => setCalendarRemoveItemConfirm(true)}>

                    <div className="dash"> &nbsp;</div>
                    <div className="start-time-text">Remove</div>
                    <div className="end-time-text"><i className="fas fa-trash-alt"></i></div>

                </div>

            </>
        )
    }

 return (
          {renderScheduleContentCell(exampleData)}
      )
  }
  
  export default PlayerCalendar;

1 个答案:

答案 0 :(得分:0)

尝试使用memo HOC并将其包装在PlayerCalendar组件周围。

React.memo可用于optimize您的组件。如果您拥有相同的props / state,则可以用来memoize the data