HCLacids / resume

1 stars 0 forks source link

React:class component 和 function component #45

Open HCLacids opened 2 years ago

HCLacids commented 2 years ago

参考链接 Capture props class组件每次获取的this.props都是最新的,而function组件由于作用域的性质,会保留他本身的变量props和state。

获取上一个 props

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return (
    <h1>
      Now: {count}, before: {prevCount}
    </h1>
  );
}

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

state 拆分过多

function FunctionComponent() {
  const [state, setState] = useState({
    left: 0,
    top: 0,
    width: 100,
    height: 100
  });
}

怎么替代 shouldComponentUpdate

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