React的capture value及useRef使用

2022-04-10  本文已影响0人  darkTi

capture value

export default () => {
  const [x, setX] = useState(0);
  const fn1 = () => {
    setX(x + 1);
  };
  const fn2 = () => {
    setTimeout(() => {
      console.log(x, "x");
    }, 3000);
  };
  return (
    <div>
      <div>测试</div>
      <button onClick={fn1}>+1</button>
      <button onClick={fn2}>3秒后显示x</button>
      x:{x}
    </div>
  );
};
export default () => {
  const [x, setX] = useState(0);
  const xref = useRef(0);  //add
  const fn1 = () => {
    setX(x + 1);
    xref.current = x + 1; //add
  };
  const fn2 = () => {
    setTimeout(() => {
      console.log(xref.current, "x"); //change
    }, 3000);
  };
  return (
    <div>
      <div>测试</div>
      <button onClick={fn1}>+1</button>
      <button onClick={fn2}>3秒后显示x</button>
      x:{x}
    </div>
  );
};

useRef

Vue3中的ref

React与Vue3的ref不同点

那么useRef可以做到变化时自动render吗?

React的理念

针对上面代码用class组件

import React from "react";
class App extends React.Component {
  constructor(props) {
    super();
    this.state = {
      x: 0
    };
  }
  fn1 = () => {
    this.setState({
      x: this.state.x + 1
    });
  };
  fn2 = () => {
    setTimeout(() => {
      console.log(this.state.x, "xxxx");
    }, 3000);
  };
  render() {
    return (
      <div className="App">
        <div>测试</div>
        <button onClick={this.fn1}>+1</button>
        <button onClick={this.fn2}>3秒后显示x</button>
        x:{this.state.x}
      </div>
    );
  }
}
export default App;
上一篇下一篇

猜你喜欢

热点阅读