我可以将 multiuseEffect 重构为Single UseEffect吗?



>我的状态宽度随着窗口大小调整和 showFilters 作为从真变为假的道具而变化。我想在卸载时删除侦听器。因此,我为每个条件使用了三个使用状态。 那么,我可以做任何重构来在单个使用效果中使用所有这些。

import React, { useEffect, useRef, useState } from 'react'
import PropTypes from 'prop-types'
import { Icon } from 'antd'
import TrendsChart from './trendsChart'
import styled from '../styled-components'
const Chart = ({ showFilters }) => {
const [width, setWidth] = useState(null)
useEffect(() => {
window.addEventListener('resize', handleWindowResize)
updateWidth()
}, [width])
useEffect(() => {
setTimeout(updateWidth, 200)
}, [showFilters])
useEffect(() => () => {
window.removeEventListener('resize', handleWindowResize)
})
const updateWidth = () => {
const containerWidth = chartRef.current.clientWidth
setWidth(Math.floor(containerWidth))
}
const handleWindowResize = () => {
updateWidth()
}
const chartRef = useRef()
function render() {
return (
<styled.chart>
<styled.chartHeader>
Daily
</styled.chartHeader>
<styled.trendsChart id="chartRef" ref={chartRef}>
<TrendsChart width={width} showFilters={showFilters}/>
</styled.trendsChart>
<div>
<Icon type="dash" />&nbsp;&nbsp;&nbsp;Credit Trend
</div>
</styled.chart>
)
}
return (
render()
)
}
Chart.propTypes = {
showFilters: PropTypes.bool.isRequired
}
export default Chart

据我所知是 你的两个使用效果可以合并

useEffect(() => {
window.addEventListener('resize',handleWindowResize)
return () => window.removeEventListener('resize',handleWindowResize)
},[width])

对于设定的超时部分,据我了解。这不是必需的,因为每次更改宽度(状态(时,react 都会重新渲染。希望有帮助。我也是新手反应。

您应该查看条件,当每个效果起作用时。

侦听器应安装一次,并进行清理:

useEffect(() => {
window.addEventListener('resize',handleWindowResize)
return () => window.removeEventListener('resize',handleWindowResize)
},[])
const handleWindowResize = () => {
const containerWidth = chartRef.current.clientWidth
setWidth(Math.floor(containerWidth))
}

注意:[]作为useEffect参数,没有此效果适用于每个渲染

。它应该足够了:

  • handleWindowResize设置窗口大小更改的宽度;
  • showFilters导致自动重新渲染

最新更新