【问题标题】:React: avoid child component rerender on state changeReact:避免子组件在状态更改时重新渲染
【发布时间】:2020-05-04 11:35:48
【问题描述】:

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

请参阅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"));

【问题讨论】:

标签: javascript reactjs react-hooks


【解决方案1】:

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

如果仅当 year 更改时才应触发副作用,则仅使用 year 作为依赖项:

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

【讨论】:

  • 我错过了 props 作为依赖项。这比使用 memo 简单得多。
  • 谢谢!另一个问题:将单个 props 属性添加为依赖项会给我一个React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array 警告。有什么需要担心的吗?
  • 不客气。从警报中删除道具。查看更新的代码。
【解决方案2】:

你正在寻找React.memo,它相当于 PureComponent,但它只比较道具。 (您还可以添加第二个参数来指定一个自定义比较函数,该函数采用新旧道具。如果返回 true,则跳过更新。)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2017-10-04
    相关资源
    最近更新 更多