react hooks(一)

useState与this.setState
  • this.setState中setTimeout能获取到新的state
  • this.setState同一时间段的会合并
  • react能控制的周期和合成事件等方法中是异步的,即执行完不会立即更新组件实例的state
  • 原生事件和setTimeout中state是同步更新的
import React from 'react';
class Page extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {}
  }
  componentDidMount() {
    this.setState({
      a:1
    })
    this.setState({
      b:2
    })
    this.setState({
      c:3
    })
    this.setState({
      c: this.state.c + 1
    })
    setTimeout(() => {
        this.setState({
          d:1
        })
        console.log(this.state.d)
        this.setState({
          d: this.state.d + 2
        })
         console.log(this.state.d)
        this.setState({
          d: this.state.d + 3
        })
        console.log(this.state.a, this.state.b,this.state.c,this.state.d)
    })
  }

  render() {
    return (
      
a:{this.state.a}
b:{this.state.b}
c:{this.state.c}
); } } export default Page;

视图结果:


image.png

console结果:


image.png

-useState的setXX的方法也会合并,且setTimeout/原生事件中合并

  • setTimeout和原生事件中不能获取到最新的state
  • 下面useState封装的setState,多个setState对不通的key也会相互覆盖
import { useEffect, useState } from "react";

export default function Page() {
   const [state, setState_] = useState({});
  const setState = (newState) => {
    setState_({
      ...state,
      ...newState
    })
  }
  const [A, setA] = useState();
  const [B, setB] = useState();
  const [C, setC] = useState();

  useEffect(() => {
    setState({
      a: 1
    })
    setState({
      b: 2
    })
    setState({
      c: 3
    })
    setA(11); setB(22); setC(33);
    setTimeout(() => {
      setState({
        c: 3
     })
      console.log(state, A, B, C)
    })
  }, [])
  return (
    <>
      
a:{state.a}
b:{state.b}
c:{state.c}

A:{A}
B:{B}
C:{C}
) }

视图结果:


image.png

console结果:

你可能感兴趣的:(react hooks(一))