ThenMorning / learn

学习笔记
0 stars 0 forks source link

React Hooks #1

Open ThenMorning opened 4 years ago

ThenMorning commented 4 years ago

1.生命周期函数如何映射到Hooks?

constructor:

class component 会在其中初始化state hooks 可以直接使用 useState初始化state

getDerivedStateFromProps:(从props中获取state,替代componentWillReceiveProps)

class component 会在其中做一些props到state的映射 hooks可以直接在函数体中使用setState方法,如下

class Foo extends Component {
    constructor(props){
       super(props);
       this.state = {
           test:false
       }
    }

    static getDerivedStateFromProps(props,state){
            if(props.flag){
                 return {
                    test : true
                  }
            }
    }
}

function Foo(props){
    const [test,setTest] = useState(false)
    if(props.flag){
       setTest(true)
    }
}

shouldComponentUpdate

class component 会在其中做一些props或state的判断用来减少组件的重新渲染 hooks可以使用memo

render

componentDidMount , componentWillUnMount , componentDidUpdate

function Foo() {
  let isRendered = useRef(0);
  useEffect(() => {
    // componentDidMount
    return () => {
      //componentWillUnMount
    };
  }, []);
  isRendered.current++;
  useEffect(() => {
    if (isRendered.current > 1) {
      // componentDidUpdate
      console.log("componentDidUpdate");
    }
  });
  return <div></div>;
}

getSnapshotBeforeUpdate,componentDidCatch, getDerivedStateFromError

暂时还无法用hooks实现

ThenMorning commented 4 years ago

2.类实例成员变量如何映射到Hooks?

class Foo{
   it = 0;
}
function Foo(){
  const it = useRef(0);
}
ThenMorning commented 4 years ago

3.Hooks中如何获取历史props和state?


function Foo() {
  const [count, setCount] = useState(0);
  const oldCount = useRef();
  useEffect(() => {
    oldCount.current = count;
  });
  return (
    <div>
      now:{count}, old:{oldCount.current}
      <div>
        <button
          onClick={() => {
            setCount(count + 1);
          }}
        >
          add
        </button>
      </div>
    </div>
  );
}
ThenMorning commented 4 years ago

4.如何强制更新一个Hooks组件?

在Hooks组件中使用一个与渲染无关的state,setState即可

ThenMorning commented 4 years ago

5.Hooks组件use方法的作用

useState处理状态 useEffect处理副作用 useContext处理跨层级传值 useMemo,useCallback处理幂等计算 useRef保存引用

ThenMorning commented 4 years ago

6.setState当前的值,Hooks组件会重新渲染么?

不会

ThenMorning commented 4 years ago

7.useEffect的第二个数组参数在都不变的情况下才不会运行副作用,如何理解这个不变?

ThenMorning commented 4 years ago

8.useEffect 如何判断多个值都改变了才执行内部方法?

ThenMorning commented 4 years ago

9.如何判定一个元素或组件在本次和上次渲染之间,有重新创建?