2 回答
TA贡献2021条经验 获得超8个赞
最好的方法是将滑块值放入 refs 中,因此更改它们不会重新渲染父级,然后单击按钮更新包含当前图表值的状态值。像这样的东西:
import React, { useCallback, useState, useRef } from 'react';
const Parent = () => {
const slider1Value = useRef(0);
const slider2Value = useRef(0);
const setSlider1Value = useCallback((value) => {
slider1Value.current = value;
}, []);
const setSlider2Value = useCallback((value) => {
slider2Value.current = value;
}, []);
const [chartValues, setChartValues] = useState({ chart1: 0, chart2: 0 });
const updateChartValues = useCallback(() => {
setChartValues({
chart1: slider1Value.current,
chart2: slider2Value.current
});
}, []);
return (
<div>
<Chart
value1={chartValues.chart1}
value2={chartValues.chart2}
/>
<Slider onChange={setSlider1Value}/>
<Slider onChange={setSlider2Value}/>
<button onClick={updateChartValues}>Apply</button>
</div>
);
}
TA贡献1810条经验 获得超4个赞
嗯,React.memo 可能是你最好的选择。像这样的事情
function RenderChart(slider1Value, slider2Value){
return (
<Chart
value1={slider1Value}
value2={slider2Value}
/>
)
}
function Parent() {
const useState [slider1Value, setSlider1Value] = useState(0);
const useState [slider2Value, setSlider2Value] = useState(0);
const useState [apply, setApply] = useState(0);
const renderedChart = useMemo(() => RenderChart(slider1Value, slider2Value), [apply])
return (
<div>
{renderedChart}
<Slider onChange={setSlider1Value}/>
<Slider onChange={setSlider2Value}/>
<button onClick={()=> setApply(true)}>Apply</button>
<div>
);
}
没有时间测试,但这对我来说就是这样的
另一种可能的(hacky)方法是设置一个占位符状态,仅当您单击“应用”按钮时才会填充该状态。
添加回答
举报