Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React:class component 和 function component #45

Open
HCLacids opened this issue Feb 28, 2022 · 0 comments
Open

React:class component 和 function component #45

HCLacids opened this issue Feb 28, 2022 · 0 comments
Labels

Comments

@HCLacids
Copy link
Owner

参考链接
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
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant