zheng há 5 dias atrás
pai
commit
710626b235

+ 5 - 2
21.react/高阶/project3/src/App.jsx

@@ -1,11 +1,14 @@
 import './App.css'
 import UseLearnState from './components/UseLearnState'
+import UseLearnEffect from './components/UseLearnEffect'
+import { useState } from 'react'
 function App() {
-
+  const [isShow, setIsShow] = useState(true)
   return (
     <>
       <h1>首页</h1>
-      <UseLearnState />
+      {/* <UseLearnState /> */}
+      {isShow ? <UseLearnEffect /> : '无内容'}
     </>
   )
 }

+ 46 - 0
21.react/高阶/project3/src/components/UseLearnEffect.jsx

@@ -0,0 +1,46 @@
+import { useEffect, useState } from "react";
+function UseLearnEffect() {
+    const [count, setCount] = useState(1);
+    const [num, setNum] = useState(2);
+    const [user, setUser] = useState({
+        name: "图图",
+        age: 3
+    })
+    useEffect(() => {
+        // 模式一:每次渲染时候执行 没有数组
+        // 不要在当前模式下修改useState定义的数据 否则会无限循环
+        console.log("你好")
+        // setCount(count + 2)
+    })
+    useEffect(() => {
+        // 模式二:仅在挂载时执行 相当于componentDidMount 空数组
+        console.log("触发")
+        setCount(count + 2)
+        // 模式四:卸载组件时触发 相当于componentWillUnmount
+        return () => {
+            console.log("哈哈哈")
+        }
+    }, [])
+    useEffect(() => {
+        // 模式三:依赖变化执行时候触发 相当于componentDidUpdate [xxx] 发生变化 触发
+        console.log("变化了")
+        document.title = `点击了${count}次`
+    }, [count])
+
+    // useEffect(() => {
+    //     // 模式三:多个依赖变化执行时候触发 相当于componentDidUpdate [xxx] 发生变化 触发
+    //     console.log("变化了")
+    //     // document.title = `点击了${count}次`
+    // }, [count, user.age])
+
+    return (
+        <div>
+            <h1>useEffect: 副作用: 与渲染无关的操作:数据请求、定时器、DOM操作、本地存储...</h1>
+            <h2 >Count:{count}</h2>
+            <h2 >Num:{num}</h2>
+            <h2 >我叫{user.name},今年{user.age}岁</h2>
+        </div>
+    )
+}
+
+export default UseLearnEffect;

+ 3 - 3
21.react/高阶/project3/src/main.jsx

@@ -4,7 +4,7 @@ import { createRoot } from 'react-dom/client'
 import App from './App.jsx'
 
 createRoot(document.getElementById('root')).render(
-  <StrictMode>
-    <App />
-  </StrictMode>,
+  // <StrictMode>
+  <App />
+  // </StrictMode>,
 )