react系列-HOOKS-UseEffect

UseEffect

useEffect 是进行批量顺序执行的。

如果两个连着的 useEffect 则是会顺序执行。

test demo:

const { useEffect, useState } = React;
const TestComponent = ({
  parentConfig
}) => {
  const [ isShow, setIsShow ] = useState(false);
  const [ config, setConfig ] = useState({});
  useEffect(() => {
    setConfig(parentConfig)
    setIsShow(false)
    console.log('first: ', isShow, parentConfig)
  }, [parentConfig])
  useEffect(() => {
    setIsShow(Object.keys(config).length > 0)
    console.log('second: ', isShow)
  }, [config])
  useEffect(() => {
    console.log('update isShow: ', isShow, '=========')
  }, [isShow])
  console.log('render TestComponent');
  return (
    isShow && <div>test</div>
  )
}

function App() {
  const [ parentConfig, setParentConfig ] = useState({a: 1});
  console.log('render App')
  return (
    <div className="App">
      <button onClick={() => setParentConfig(Object.keys(parentConfig).length > 0 ? {} : {a: 1})}>
        switch parentConfig
      </button>
      <TestComponent parentConfig={parentConfig} />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

初始渲染的日志顺序:

WX20211213-230845@2x