React函数式组件避免无用渲染的方案

发布时间 2024-01-03 16:28:40作者: 从前有匹马叫代码

在class组件中可以使用shouldComponentUpdate钩子函数,但是函数式组件中是没有这种钩子函数的,那么在函数式组件中来达到类似的效果呢?
答案是:React.Memo,如以下使用案例:

// 父组件
const [values, setValues] = useState({
    a: 1,
    b: 1,
  });
  function increment() {
    setValues({
      ...values,
      a: values.a + 1,
    });
  }
<Button onClick={increment}>增加</Button>
 <NextComponent value={values.a} />
 
 
 
// 子组件
import React from "react";
interface Props {
  value: number;
}

const NextComponent: React.FC<Props> = (props) => {
  console.log("rerender");
  return <div>{props.value > 5 ? "大于五" : "小于五"}</div>;
};

const MemoNextComponent = React.memo(
  NextComponent,
  (prevProps: Readonly<Props>, nextProps: Readonly<Props>) => {
    const prev = prevProps.value - 5 > 0;
    const next = nextProps.value - 5 > 0;
    return prev == next;
  },
);

export default MemoNextComponent;

通过React.Memo提供的第二个参数,来判断是否不需要更新,如果true,则直接跳过组件更新,反之则重新渲染组件。