反应:避免在状态更改时重新渲染子组件

时间:2020-01-17 14:53:29

标签: javascript reactjs react-hooks

我正在开发一个React应用,其中图形组件使用从父组件传递来的prop来获取并显示数据。问题在于,父级也会进行某些数据提取,并且更新父级状态(尽管不影响子级props)似乎会重新渲染子级,从而在子级中启动重复数据提取。

有关代码,请参见https://jsfiddle.net/ctombaugh/cgzn7wst/10/及以下内容。

function App(props) {
  const [year, setYear] = React.useState(2019);
  const [list, setList] = React.useState([]);
  React.useEffect(() => {
    alert("App is fetching some lists");
    setList(["a", "b", "c"]);
  }, [setList]);
  function handleYearChange(e) {
    setYear(e.target.value);
  }
  return (<div>
    <YearSelector value={year} onChange={handleYearChange}></YearSelector>
    <Plot year={year}></Plot>
  </div>);
}

function YearSelector(props) {
  return <select value={props.value} onChange={e => props.onChange(e)} >
    <option value="2019">2019</option>
    <option value="2018">2018</option>
  </select>
}

function Plot(props) {
  const [data, setData] = React.useState([]);
  React.useEffect(() => {
    alert("Plot is fetching data for " + props.year);
    setData([1, 2, 3]);
  }, [props]);
  return <div>I'm a plot</div>;
}

ReactDOM.render(<App/>, document.getElementById("container"));

2 个答案:

答案 0 :(得分:3)

每当重新呈现组件时,都会生成一个新的pthread_sigmask对象,因此使用props作为对props的依赖并没有真正的帮助。

如果仅在useEffect发生变化时才产生的副作用,请仅将year用作依赖项:

year

答案 1 :(得分:1)

您正在寻找与PureComponent等效的React.memo,但它仅比较道具。 (您还可以添加第二个参数来指定使用旧道具和新道具的自定义比较函数。如果返回true,则跳过更新。)

const Button = React.memo((props) => {
  // your component
});

有关更多信息,https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-shouldcomponentupdate